There is a thread for "Adding a prefix to column names", but the solutions are limited to adding fixed strings as the prefix or postfix. Is is possible to add the value of another column as a prefix to a column name?
For example, I have a column named sum
, and another column named time_period
with values of year
, and month
, depending on the dataframe. I am hoping to create new columns like year_sum
and month_sum
dynamically. A dplyr
solution would be ideal but not necessary.
Already tried the following thread and related threads: Adding a prefix to column names
df <- tibble(sum = c(150, 175, 200), time_period = c('year', 'year', 'year')) %>%
rename_at(vars(sum), function(x) paste0(time_period, x)) %>%
glimpse()
I get the following error:
Error in paste0(time_period, x) : object 'time_period' not found
I am expecting that column sum
is renamed to year_sum
.