[datatable-help] Calling [.data.table from another function

Matthew Dowle mdowle at mdowle.plus.com
Tue Jul 26 21:23:12 CEST 2011


Hi Chris,

That doesn't sound right to me.  That thread highlighted a scoping bug,
long fixed. You don't need to put the data.table inside the function,
doesn't sound like it will work.

How about this (tested) :

> x <- data.table(iris)
> setkey(x,Species)
> b <- function(x, expr) {
+     e = substitute(expr)
+     x[,eval(e),by=Species]
+ }
> b(x,sum(Sepal.Width))
        Species    V1
[1,]     setosa 171.4
[2,] versicolor 138.5
[3,]  virginica 148.7
> 

Matthew

On Tue, 2011-07-26 at 00:53 -0700, Chris DuBois wrote:
> Apologies everyone, but I did not search well enough.
> 
> 
> I found this post extremely
> informative: http://r.789695.n4.nabble.com/Passing-user-defined-functions-as-part-of-the-j-argument-td2714377.html#a2715158
> 
> 
> By creating the data.table inside the function, Sepal.Width was now
> available in the proper environment.
> 
> 
> Chris
> 
> On Mon, Jul 25, 2011 at 10:27 PM, Chris DuBois
> <chris.dubois at gmail.com> wrote:
>         Hi all,
>         
>         
>         I'm trying to use the DT[,,by=] interface within a function,
>         and I get an error.  I understand that Sepal.Width is not
>         available in the needed environment.  Is there a way to
>         circumnavigate this and use [.data.table() within a function?
>          (Note: I'm trying to get my head around substitute, eval,
>         etc., so I'm sorry if this is obvious!)
>         
>         
>         Here's a (hopefully) reproducible example:
>         
>         
>         x <- data.table(iris)
>         setkey(x,Species)
>         x[,sum(Sepal.Width),by=Species]  # correct answer
>         
>         
>         b <- function(x, expr) {
>           x[, expr,by=Species]
>         }
>         b(x,sum(Sepal.Width))
>         # Error in eval(expr, envir, enclos) : object 'Sepal.Width'
>         not found
>         
>         
>         Thanks in advance for any insight into this issue.
>         Chris
> 
> 





More information about the datatable-help mailing list