一个可能的解决方案是在函数中使用mget
,直到返回列表,然后将xyz
与带有c
的列表合并。您需要将要添加的列指定为字符向量才能完成此工作:
getvar = function(...){
return(d[,c(xyz = mean(hp),mget(...)),cyl])
}
getvar(c("mpg","cyl","disp"))
给出:
> getvar(c("mpg","disp"))
cyl xyz mpg cyl disp
1: 6 122.28571 21.0 6 160.0
2: 6 122.28571 21.0 6 160.0
3: 6 122.28571 21.4 6 258.0
4: 6 122.28571 18.1 6 225.0
5: 6 122.28571 19.2 6 167.6
6: 6 122.28571 17.8 6 167.6
7: 6 122.28571 19.7 6 145.0
8: 4 82.63636 22.8 4 108.0
9: 4 82.63636 24.4 4 146.7
10: 4 82.63636 22.8 4 140.8
....
或者作为替代方案,@Rhonak's answer(@ zx8754的thx)略有变化:
getvar = function(...){
mc <- match.call(expand.dots = FALSE)
x <- as.character(mc$...)
d[,mget(x)),cyl]
}
getvar(mpg,cyl,disp)
,
要在不引用列名的情况下使其工作,您必须使用一些非标准的评估策略:
getvar = function(...){
vars <- substitute(list(xyz = mean(hp),...))
return(d[,eval(vars),cyl])
}
getvar(mpg,disp)
cyl xyz mpg cyl disp
1: 6 122.28571 21.0 6 160.0
2: 6 122.28571 21.0 6 160.0
3: 6 122.28571 21.4 6 258.0
4: 6 122.28571 18.1 6 225.0
5: 6 122.28571 19.2 6 167.6
...etc...
,
以@Konrad Rudolph here的答案为基础,我们可以编写函数
getvar = function(...){
dots = match.call(expand.dots = FALSE)$...
cols = sapply(dots,deparse)
d[,mget(cols)),cyl]
#thanks to @Jaap for simplified version
}
getvar(mpg,disp)
# cyl xyz mpg cyl disp
# 1: 6 122.29 21.0 6 160.0
# 2: 6 122.29 21.0 6 160.0
# 3: 6 122.29 21.4 6 258.0
# 4: 6 122.29 18.1 6 225.0
# 5: 6 122.29 19.2 6 167.6
# 6: 6 122.29 17.8 6 167.6
#....
本文链接:https://www.f2er.com/3161597.html