Skip to content

Instantly share code, notes, and snippets.

@kelly-sovacool
Last active September 22, 2022 14:52
Show Gist options
  • Save kelly-sovacool/76f55426963b04bfb102381fd9a70b67 to your computer and use it in GitHub Desktop.
Save kelly-sovacool/76f55426963b04bfb102381fd9a70b67 to your computer and use it in GitHub Desktop.
How to use a data variable to name a new column name with tidy eval
library(tidyverse)
f <- function(dat, colname) {
varname <- rlang::as_name(rlang::enquo(colname))
new_df <- data.frame(x = c('a','b','c')) %>%
mutate({{varname}} := dat %>% pull({{ colname }}))
return(new_df)
}
df1 <- data.frame(a = 1:3, b = 4:6)
df1 %>% f(a)
df1 %>% f(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment