并行循环R

时间:2013-11-27 10:21:26

标签: r parallel-foreach

我在for循环中调用一个函数。

sample_fun <- function(x,y) {
    # do something with x,y and return value
}

My loop looks like
result = list()

for(i in 1:10000)
   result[i] = sample_fun(i,i+1)

如何并行化此循环。使用foreach和dopar给出了下标错误。

1 个答案:

答案 0 :(得分:6)

library(doSNOW)

sample_fun <- function(x,y) {
  # do something with x,y and return value
}

threads <- 8
N <- 10000

cl <- makeCluster(threads)
registerDoSNOW(cl)

result <- foreach(i=1:N) %dopar% sample_fun(i,i+1)

stopCluster(cl)

http://www.joyofdata.de/blog/parallel-computing-r-windows-using-dosnow-foreach/