0

I tried to write a fuction with data.table and here's an example about the idea:

d <- data.frame(x=1:6, y=6:1, z= rep(c('A', 'B', 'C'), 2))
func <- function(q){
    o <- setDT(d)[, list(maxi = max(q)), by = z]
}
func(x)

the returned error said object x can't be found. I looked at this and this, tried do.call and data.frame selection, with no good result:

o <- setDT(d)[, maxi = do.call('max', list(q)), by = z]
o <- setDT(d)[, maxi = do.call('max', list(d$q)), by = z]
o <- setDT(d)[, list(maxi = max(d[,q])), by = z]

it returned "unused argument", "object not found", or "invalid 'type' (closure) of argument". Am I following the previous answers wrong or data.table needs some special tuning? To see if this only happens with data.table, I also tested o <- aggregate(d[, q] ~ z, d, max) and the result was no good either. Thanks for any help!

Community
  • 1
  • 1
leoce
  • 715
  • 1
  • 8
  • 24
  • What's surprising about it? If `x` doesn't exist, how can one evaluate `func(x)`? – nicola Dec 25 '15 at 09:21
  • 5
    Change your function to `data.table(d)[, .(maxi = max(get(q))), by = z]` (you don't need `o <- ` ) and then run `func("x")`. See [here](http://stackoverflow.com/questions/27677283/evaluating-both-column-name-and-the-target-value-within-j-expression-within-d) for some alternatives. – David Arenburg Dec 25 '15 at 09:22
  • Or you can try use `lazyeval` package `func <- function(q){ q=lazy(q) o <- setDT(d)[, list(maxi = max(eval(q$expr))), by = z] return(o) }` – Batanichek Dec 25 '15 at 09:36

0 Answers0