plyr functions and standard evaluation

110 views Asked by At

I would like to wrap plyr functions in my own functions. I want to pass to the function an object and the variable (unquoted) on which apply a cut function.

x <- data.frame(time = seq(Sys.Date() - 99, Sys.Date(), 1))

dlply(x, .(week = cut(time, "1 week")), "[")

f <- function(datas, var) {
  var <- deparse(substitute(var))

  dlply(x, .(week = cut(var, "1 week")), "[")
}

f(x, time) # fail

I don't know how to use the object var to specify as variable his value and not "var" as a variable, within ddply.

Unlike in dplyr there is no standard evaluation versions of plyr functions ? I read that I can use strings, but for example dlply(x, .(week = cut("time", "1 week")), "[") fails

I also tried lazyeval, but I'm lost in the standard/non standard evaluation universe.

1

There are 1 answers

0
shadow On BEST ANSWER

You seem to have an unnecessary deparse in your code and you don't evaluate var in the right place. It works with the following.

f <- function(datas, var) {
  var <- substitute(var)
  dlply(datas, .(week = cut(eval(var), "1 week")), "[")
}