【问题标题】:Parallelizing a double for loop in R在 R 中并行化双 for 循环
【发布时间】:2014-04-12 20:28:03
【问题描述】:

我一直在 R 中使用 parallel 包来执行以下循环:

cl <- makeCluster(getOption("cl.cores", 6))
result <- parSapply(cl,1:k,function(i){ ... })

有没有一种自然的方法可以使用这个包在 R 中并行化嵌套的 for 循环?或者也许是另一个包裹?我知道有几种方法可以在 R 中实现并行性。

我的循环看起来像这样。我简化了一点,但它传达了信息:

sup_mse <- matrix(0,nrow=k,ncol=length(sigma))
k <- 100000 #Number of iterations
sigma <- seq(from=0.1,to=10,by=0.2)

for(i in 1:k){
  for(j in 1:length(sigma)){
    sup<-supsmu(x,y)
    sup_mse[i,j] <- mean((m(x)-sup$y)^2)
  }
}

【问题讨论】:

  • 您能否提供一个可重现的示例,说明您希望并行尝试的嵌套循环类型?

标签: r for-loop parallel-processing nested-loops


【解决方案1】:

感谢您制作可重现的示例!我更喜欢降雪来进行并行处理,所以这里是它的样子。

install.packages('snowfall')
require(snowfall)

### wasn't sure what you were using for x or y
set.seed(1001)
x <- sample(seq(1,100),20)
y <- sample(seq(1,100),20)
k <- 100
sigma <- seq(0.1, 10, 0.2)

### makes a local cluster on 4 cores and puts the data each core will need onto each
sfInit(parallel=TRUE,cpus=4, type="SOCK",socketHosts=rep("localhost",4))
sfExport('x','y','k','sigma')

answers <- sfSapply(seq(1,k), function(M) 
  sapply(seq(1,length(sigma)), function(N)
    mean((mean(x)-supsmu(x,y)$y)^2)  ## wasn't sure what you mean by m(x) so guessed mean
  )
)

sup_mse <- t(answers) ## will give you a matrix with length(sigma) columns and k rows
sfStop()

我记得在某处读到您只想在外部循环中使用sfSapply,然后在该循​​环内使用常规应用函数。希望这会有所帮助!

【讨论】:

  • 谢谢,对不起,我没有包括所有的细节!这应该足以弄清楚
猜你喜欢
  • 2015-09-04
  • 1970-01-01
  • 2010-12-06
  • 2013-12-12
  • 1970-01-01
  • 2017-07-01
  • 2016-11-14
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多