开发者

Extracting lapply or mclapply results

I am currently running numerous apply lines that look like this:

test=data.frame(t=seq(1,5,1),e=seq(6,10,1))
mean(apply(test,2,mean))

I want to convert the second line to mclapply which produces the same result as lapply. I realize that I could extract each item from the lapply statement using a for loop then use mean on that vector but that would slow down performance which I am trying to improve by using mclapply. The problem is both lapply and mcapply return a list which mean cannot use. I can either use [[]] to get the actual value or test$t and test$e but the number of columns in test is variable and typically runs over 1,000. There must be an easier way to handle this. Basically I want to get 开发者_开发百科the mean of this statement:

mclapply(test,mean,mc.preschedule=TRUE)

preferably without generating new variables or using for loops. The solution should be equivalent to getting the mean of this statement:

lapply(test,mean)


I'm confused -- a data.frame is after all list as well. So besides the obvious

R> testdf <- data.frame(t=seq(1,5,1),e=seq(6,10,1))
R> mean(testdf)
t e 
3 8 
R> mean(mean(testdf))
[1] 5.5
R> 

you could also do

R> lapply(testdf, mean)
$t
[1] 3

$e
[1] 8

R> mean(unlist(lapply(testdf, mean)))
[1] 5.5
R> 

So there for the inner lapply you could use mclapply as desired, no?


I like to put the mclapply() results in a list, and then combine those lists to form a final product:

results.list <- list()
results.list <- mclapply(listOfData, analysisFunction, mc.cores = 7)

library(data.table)
result <- rbindlist(results.list) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜