r - Pass vector of column names to paste() within mutate (dplyr) -


i'm trying write function takes 1 of arguments vector of column names user. column names used specify columns of dataframe pasted form new column within dplyr::mutate. tried collapse elements of argument vector first , use collapsed string in mutate - wrong. see latest attempt below. made other attempts i'm not understanding new quo, enquo, uq, !!!, !!, , on within dplyr. can show need do?

df <- data.frame(.yr = c("2000", "2001", "2002"), .mo = c("12", "01", "02"), .other = rnorm(3)) cols <- colnames(df)[1:2]  do_want <- df %>%   mutate(new = paste(.yr, .mo, sep = "-"))  my_func <- function(dat, vars){   .vars <- paste(vars, collapse = ",")    result <- dat %>%     mutate(new = paste(.vars, sep = "-" ))   return(result) }  my_func(dat = df, vars = cols) 

edit: attempt @ using quo , !! in function definition. result column of repeated string ".yr,.mo"

my_func <- function(dat, vars){   .vars <- quo(paste(vars, collapse = ","))    result <- dat %>%     mutate(new = paste(!!.vars, sep = "-" ))   return(result) } 

because have list of strings, can use rlang::syms in function take strings , turn them symbols. can use !!! splice arguments put paste.

my_func <- function(dat, vars){      .vars <- rlang::syms(vars)       result <- dat %>%           mutate(new = paste(!!!.vars, sep = "-" ))      return(result) }  my_func(dat = df, vars = cols)     .yr .mo     .other     new 1 2000  12 -0.2663456 2000-12 2 2001  01  0.5463433 2001-01 3 2002  02 -1.3133078 2002-02 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -