Have `rename` recognize a variable value as a column name

I am trying to rename a column using the rename function but I want to use a variable to assign the column name so I can change the column name programmatically within a for loop.

Here's a pseudo code example of what I am trying to accomplish:
If data is the format

id, value
1, 300
2, 500
3, 450
....

Then I want to be able to do this

col_name = 'abc_value'

data = data %>%
    rename(col_name = value)

So that data is now of the format

id, abc_value
1, 300
2, 500
3, 450
....

But I keep getting data as :

id,col_name
1, 300
2, 500
3, 450
....

which I don't want.

I have also tried rename(!!sym(col_name) = value but that just gives me an error. I am not sure how to change the column name using a variable assignment.

One approach is to use "dynamic dots" features from rlang. It would work like this:

library(tidyverse)

data <- tribble(
  ~id, ~value,
  1, 300,
  2, 500,
  3, 450
)

col_name <- "abc_value"

data |> 
  rename("{col_name}" := value)
#> # A tibble: 3 × 2
#>      id abc_value
#>   <dbl>     <dbl>
#> 1     1       300
#> 2     2       500
#> 3     3       450

Created on 2023-07-07 with reprex v2.0.2

There is some discussion of this in the Programming with dplyr vignette.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.