Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formula evaluation with mutate()

Tags:

r

dplyr

plyr

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?

like image 295
paljenczy Avatar asked Apr 07 '14 09:04

paljenczy


1 Answers

If you want expression input

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)

If you want character input

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")

You can also modify the functions to take the name of z as an input.

Expression input: f1 passes all extra parameters to mutate, f2 only passes one argument to 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)

Again, if you want to use character input

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")
like image 122
Randy Lai Avatar answered Sep 21 '22 13:09

Randy Lai