I have a basic question on how to optimize the following code. This is a very very abbreviated version of my code. Basically, I have a large data.table (> 50M rows) and I would like to subset the data very often (say 10000 times) and run some function on the subset (obviously more complicated than the one shown in the example below, i.e. I need all columns of the subset and the function returns a new data.table). I just picked the mean to make the example simple.
dt <- data.table(a=sample(letters, 1000000,replace=T),b=sample(1:100000))
mm <- list()
foo <- function(x) mean(x$b)
for(i in 1:1000)
{
mm[[i]] <- foo(dt[a %in% sample(letters,5)])
}
It is obvious that this is not the fastest way to program even this minimal example (setting keys etc.).
I am interested, however, how to optimize the for loop. I had in mind to create indices for the subsets and then use data.table dt[,foo(.SD),by=subset_ID] , but I am not sure on how to this, since I am sampling with replacement (multiple group IDs). Any ideas based on data.table would be much appreciated (e.g. how to remove the loop?).