使用mutate()进行公式评估

pal*_*czy 4 r plyr dplyr

有没有办法mutate()在(d)plyr包装中制作评价公式?我想到一个有很多变量的情况,count.a, count.b, ..., count.z我想创建一个新变量来总结所有这些.我可以创建一个字符串"count.total = count.a + count.b + (...) + count.z",但是如何mutate()评估呢?

Ran*_*Lai 7

如果你想要表达式输入

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)
Run Code Online (Sandbox Code Playgroud)

如果你想要字符输入

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")
Run Code Online (Sandbox Code Playgroud)

您还可以修改函数以将名称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)
Run Code Online (Sandbox Code Playgroud)

同样,如果你想使用字符输入

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")
Run Code Online (Sandbox Code Playgroud)