[datatable-help] Passing user defined functions as part of the j argument

Damian Betebenner dbetebenner at nciea.org
Sun Sep 26 16:21:39 CEST 2010


I'm running into scoping issues and instead of doing "trial and error" for the next several hours, thought I would ask
for some help to understand the bigger issue.

Within a function I have several functions. Within one of those functions I call one of the other defined functions using data.table.
The issue is that I can't find the function that I'm calling as part of the j expression in data.table.

Here's a simple example:


require(data.table)
test.data <- data.table(ID=rep(1:2,  each=10), SCORE=rnorm(20))

test.fun <- function(my.data) {

my.mean <- function(x) {
       mean(x, na.rm=TRUE)
}

my.data[,my.mean(SCORE), by=ID]

}


> test.fun(test.data)
Error in eval(expr, envir, enclos) : could not find function "my.mean"
>


My situation involves calling a function much more complicated than "my.mean". So my question is, how can I get access to the function "my.mean" within data.table.

A more realistic example that includes the outer function is as follows:


#1 Try to explicitly pass the function

outer.function <- function(ss.data) {

   test.data <- as.data.table(ss.data)

   my.mean <- function(x) {
          mean(x, na.rm=TRUE)
   }

   test.fun <- function(my.data, my.function) {
        my.data[,my.function(SCORE), by=ID]
   }

   my.result <- test.fun(test.data, my.mean)
  return(my.result)
}

outer.function(data.frame(ID=rep(1:2,  each=10), SCORE=rnorm(20)))

Error in eval(expr, envir, enclos) :
  could not find function "my.function"



#2 Try to see if somehow the function "my.mean" gets found.


outer.function <- function(ss.data) {

   test.data <- as.data.table(ss.data)

   my.mean <- function(x) {
          mean(x, na.rm=TRUE)
   }

   test.fun <- function(my.data) {
        my.data[,my.mean(SCORE), by=ID]
   }

   my.result <- test.fun(test.data)
   return(my.result)
}

outer.function(data.frame(ID=rep(1:2,  each=10), SCORE=rnorm(20)))

Error in eval(expr, envir, enclos) : could not find function "my.mean"


Any help in better understanding the scoping rules would be greatly appreciated.

Best regards,

Damian


Damian Betebenner
Center for Assessment
PO Box 351
Dover, NH   03821-0351

Phone (office): (603) 516-7900
Phone (cell): (857) 234-2474
Fax: (603) 516-7910

dbetebenner at nciea.org<mailto:dbetebenner at nciea.org>
www.nciea.org<http://www.nciea.org/>



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20100926/1becd7db/attachment.htm>


More information about the datatable-help mailing list