Is there a way to make mutate()
evaluate formulas in (d)plyr package of R? I think of situations where one has many variables like count.a, count.b, ..., count.z
and I would like to create a new variable to sum all these. I can create a character string like "count.total = count.a + count.b + (...) + count.z"
, but how to make mutate()
evaluate it?
问问题
1487 次
1 回答
10
如果你想要表达式输入
library(dplyr)
df = data.frame(x = 1:10, y = 2:11)
f = function(df, s){
eval(substitute(mutate(df, z = s)))
}
f(df, x-y)
f(df, x+y)
如果你想输入字符
g = function(df, s){
q = quote(mutate(df, z = s))
eval(parse(text=sub("s", s, deparse(q))))
}
g(df, "x-y")
g(df, "x+y")
您还可以修改函数以将名称z
作为输入。
表达式输入:f1
将所有额外参数传递给mutate
,f2
仅将一个参数传递给mutate
。
f1 = function(df, ...){
mutate(df, ...)
}
f1(df, a = x-y)
f2 = function(df, ...){
dots = substitute(alist(...))
var = names(dots)[2]
cal = as.call(list(quote(mutate), quote(df)))
cal[var] = dots[2]
eval(cal)
}
f2(df, a = x-y)
同样,如果您想使用字符输入
g1 = function(df, s){
q = quote(mutate(df, z = s))
eval(parse(text=sub("z = s", s, deparse(q))))
}
g1(df, "a=x-y")
g1(df, "w=x+y")
于 2014-04-07T10:58:33.877 回答