Reputation:
my dataframe looks like this
df <-
data.frame(
date = c("2020-01-01", "2020-02-01"),
id = c(1, 2),
sold = c(100, 200),
country = c("us", "eu")
)
I'd like to rename date, id and sold columns by pasting my var value and actual colname so result would be
var = "rename_to"
result <-
df <-
data.frame(
rename_to_date = c("2020-01-01", "2020-02-01"),
rename_to_id = c(1, 2),
rename_to_sold = c(100, 200),
country = c("us", "eu")
)
Please I'm looking for some dplyr solution.
Upvotes: 0
Views: 95
Reputation: 388817
You can use rename_with
:
library(dplyr)
df %>% rename_with(~paste(var, ., sep = '_'), .cols = c(date, id, sold))
# rename_to_date rename_to_id rename_to_sold country
#1 2020-01-01 1 100 us
#2 2020-02-01 2 200 eu
Upvotes: 1