我正在尝试编写一个函数,该函数将用户的列名称向量作为其参数之一。列名称将用于指定数据帧的哪些列将粘贴在一起以形成 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)
编辑:这是我尝试使用现状和!!在函数定义中。结果是一列重复的字符串“.yr,.mo”
my_func <- function(dat, vars){
.vars <- quo(paste(vars, collapse = ","))
result <- dat %>%
mutate(new = paste(!!.vars, sep = "-" ))
return(result)
}
最佳答案
因为您有一个字符串列表,所以您可以在函数中使用 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
关于r - 将列名称向量传递给 mutate (dplyr) 中的 Paste(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45686250/