Is it possible to refer to a variable name after renaming it using tidy evaluation? As an example, I would like to write a function that does the same as the following code but allows to specify the new variable name in a function argument:
library(tidyverse)
mtcars %>%
rename(cylinder = cyl) %>%
group_by(cylinder) %>%
summarize(mean_mpg = mean(mpg))
However, I am stuck in the group_by
line (in the code below) because neither !!varname
nor {{ varname }}
works as a replacement for the question marks. I assume that !!varname
does not work because it expands to a character string; and that {{ varname }}
does not work because no column with the new name exists when the function is called. I don't see a way to use the glue
syntax either because nothing is being assinged in that line.
my_rename <- function(df, varname) {
df %>%
rename("{varname}" := cyl) %>%
group_by(???) %>%
summarize(mean_mpg = mean(mpg))
}