将列名称的向量传递给mutate中的paste()(dplyr)

mb1*_*127 4 r dplyr rlang

我正在尝试编写一个函数,它将来自用户的列名称向量作为其参数之一.列名将用于指定将数据帧的哪些列粘贴在一起以在dplyr :: mutate中形成新列.我试图首先折叠参数向量的元素,然后在mutate中使用折叠的字符串 - 这是错误的.请参阅下面的最新尝试.我做了其他尝试,但我不理解dplyr中的新quo,enquo,UQ,!!!,!!等等.有人可以展示我需要做什么吗?

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)
Run Code Online (Sandbox Code Playgroud)

编辑:这是我尝试使用quo和!! 在函数定义中.结果是一列重复的字符串".yr,.mo"

my_func <- function(dat, vars){
  .vars <- quo(paste(vars, collapse = ","))

  result <- dat %>%
    mutate(new = paste(!!.vars, sep = "-" ))
  return(result)
}
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 7

因为您有一个字符串列表,所以您可以rlang::syms在函数中使用字符串并将它们转换为符号.然后你可以!!!用来拼接参数放在一起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
Run Code Online (Sandbox Code Playgroud)