L Smeets
L Smeets

Reputation: 942

How to rename column based on value of the first row of another column in dplyr pipe

I have a long pipe of different filtering and selecting functions, and in that same pipe operation, I would like to rename a column based on the value in the first row of another column. I have to do this for many different data frames, so a pipeline that is agnostic to the name of the data frame would be nice.

This is a small example:

original <- tibble(value = c(1,2,4,6,7), month = 1:5, year = 2018)
what_I_want <- tibble(indicator2018 = c(1,2,4,6,7), month = 1:5, year = 2018)

So if the first row of the column year would have been 2015, then the column name of value would have changed to indicator2015.

This doesn't work:

original %>%
  rename(paste0("indicator", .$year[1]) = "value")

original %>%
  rename_at(vars(starts_with("value")), list( ~ str_replace(., "value", paste0("indicator", .["year"][1]))))

This works but involves breaking the pipe and (more importantly) requires the name of the data frame in the pipe, so would not scale to many different data frames without manually changing the code.

original2 <- original %>%
  rename_at(vars(starts_with("value")), list( ~ str_replace(., "value", paste0("indicator", original$year[1]))))

Upvotes: 3

Views: 931

Answers (1)

Peter H.
Peter H.

Reputation: 2164

You need to do some unquoting. This works:

original %>% 
  rename(!!paste0("indicator", .$year[1]) := "value")

For future reference, I would suggest that you check out the "programming with dplyr" vignette (https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html).

Upvotes: 4

Related Questions