将列名称的向量传递给mutate(dplyr)中的paste() [英] Pass vector of column names to paste() within mutate (dplyr)
问题描述
我正在尝试编写一个函数,该函数将用户的列名向量作为其参数之一。列名称将用于指定将数据框的哪些列粘贴在一起以在dplyr :: mutate中形成新列。我尝试先折叠参数向量的元素,然后在mutate中使用折叠的字符串-这是错误的。请参阅下面的最新尝试。我进行了其他尝试,但是我不了解dplyr中的新quoU,enquo,UQ,!!!,!!等。有人可以显示我需要做什么吗?
I'm trying to write a function that takes as one of its arguments a vector of column names from user. The column names will be used to specify what columns of the dataframe will be pasted together to form a new column within dplyr::mutate. I tried to collapse the elements of argument vector first and then use the collapsed string in mutate - this is wrong. See that latest attempt below. I made other attempts but I'm not understanding the new quo, enquo, UQ, !!!, !!, and so on within dplyr. Can someone show what I need to 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)
编辑:这是我尝试使用quo和!!在函数定义中。结果是一列重复的字符串 .yr,.mo
edit: this is my attempt at using quo and !! in the function definition. the result is a 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)
}
推荐答案
因为您有一个字符串列表,所以可以在函数中使用 rlang :: syms
来获取字符串并转换它们变成符号。然后,您可以使用 !!!
将参数拼接在一起以放入 paste
。
Because you have a list of strings, you can use rlang::syms
in your function to take the strings and turn them into symbols. Then you can use !!!
to splice the arguments together to put into 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
这篇关于将列名称的向量传递给mutate(dplyr)中的paste()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!