2

有很多方法可以将函数应用于每一行。

这里有一些我知道的方法:

方法一

for (i in 1:nrow(data) ) { my_function(data[i,]) }

方法二

apply(data,1,my_function)

方法三

library(plyr)
adply(data,.margins=1, .fun=my_function)

方法四

library(doParallel)
nodes <- detectCores()
cl <- makeCluster(nodes)
registerDoParallel(cl)
clusterEvalQ(cl,source("my_fun.R"))
adply(data,.margins=1, .parallel = T, .fun=my_function)
stopCluster(cl)

在前 3 种方法中,我认为更快的是第三种方法。但问题是:方法 4(并行方法)何时比方法 3 快?有没有办法在运行所有代码之前理解它?

4

0 回答 0