我试图编写一个函数,该函数将来自用户的列名称作为其参数之一。列名将用于指定将数据帧的哪些列粘贴在一起以在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)
编辑:这是我尝试使用quo和!!在函数定义中。结果是一列重复的字符串&#34; .yr,.mo&#34;
my_func <- function(dat, vars){
.vars <- quo(paste(vars, collapse = ","))
result <- dat %>%
mutate(new = paste(!!.vars, sep = "-" ))
return(result)
}
答案 0 :(得分: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
答案 1 :(得分:0)
使用mutate_
代替mutate
&amp;将表达式转换为适合我的字符串:
dplyr_solution <- function(dat, vars){
.vars <- paste(vars, collapse = ",")
result <- dat %>%
mutate_(new = paste0('paste(', .vars, ', sep="-")'))
return(result)
}
dplyr_solution(dat = df, vars = cols)
答案 2 :(得分:0)
团结起来。
if (document.getElementById(temp).checked == false) {
columns[i].cssClass = "reallyHidden";
columns[i].headerCssClass = "reallyHidden";
columns[i].maxWidth = 1;
var classString = columns[i].name + "_class";
var widthString = columns[i].name + "_width";
localStorage.setItem(classString, "reallyHidden");
localStorage.setItem(widthString, "1");
// localStorage.setItem(columns[i].name, columns[i].minWidth);
}
if (document.getElementById(temp).checked == true) {
var classString = columns[i].name + "_class";
if (localStorage.getItem(classString) != null) {
columns[i].cssClass = null
columns[i].headerCssClass = null
columns[i].maxWidth = null;
var widthString = columns[i].name + "_width";
localStorage.setItem(classString, "null");
localStorage.setItem(widthString, "null");
}
}