1

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.

Cettt
  • 11,460
  • 7
  • 35
  • 58
Jim
  • 23
  • 5
  • Can you show us your expected output? – arg0naut91 Nov 01 '19 at 15:03
  • Can you show what your expected output would look like? Preferably with an example that also includes month in the time period. – kath Nov 01 '19 at 15:03
  • What happens if `time_period` has values other than `year`? – deepseefan Nov 01 '19 at 15:07
  • For the example above, my expected output would be: year_sum time_period 150 year 11 year 14 year. If the time_period had values of "month" instead, I would expect: month_sum time_period 150 month 11 month 14 month. For my exact dataframe, the solution from @Cettt actually should do the trick as I'm not expecting mixed values of time_period within each dataframe. This solution is going into a generalized function which is why I'd like it to be dynamic. (Sorry not sure if this format is valid - first post on SO and trying to figure out the markdown formatting now). – Jim Nov 01 '19 at 16:42

1 Answers1

-1

Here is a workaround solution. It only looks at the first row of time_period and takes what ever value it finds there:

df %>% {rename_at(., vars(sum), function(x) paste(pull(., time_period)[1], x, sep = "_"))}

# A tibble: 3 x 2
  year_sum time_period
     <dbl> <chr>      
1      150 year       
2      175 year       
3      200 year 
Cettt
  • 11,460
  • 7
  • 35
  • 58