plyr functions and standard evaluation

时间:2015-06-25 10:00:48

标签: r plyr nse standard-evaluation

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 个答案:

答案 0 :(得分:1)

您的代码中似乎有一个不必要的deparse,并且您没有在正确的位置评估var。它适用于以下内容。

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