Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么for循环不能并行工作?_R_Parallel Processing - Fatal编程技术网

为什么for循环不能并行工作?

为什么for循环不能并行工作?,r,parallel-processing,R,Parallel Processing,我试图在linux版本的R中并行运行一个函数。但是,我不断发现每个并行迭代都返回NULL,而不是函数的输出。我已将问题隔离到for循环 以下是一个简化版本: library(parallel) rows <- seq(1,9,1) for_test <- function(i){ for (s in 1:3){ print(i*s) } } cls <- makeCluster(length(rows), type = 'FORK') parLappl

我试图在linux版本的R中并行运行一个函数。但是,我不断发现每个并行迭代都返回
NULL
,而不是函数的输出。我已将问题隔离到for循环

以下是一个简化版本:

library(parallel)

rows <- seq(1,9,1)

for_test <- function(i){
  for (s in 1:3){
    print(i*s) 
  }
}

cls <- makeCluster(length(rows), type = 'FORK')

parLapply(cls, rows, for_test)

stopCluster(cls)

返回
i*s
的结果,而不是
NULL
。我以前在parallel中运行过循环,但似乎不明白为什么它在这种情况下不起作用。有人能指出我的错误吗?

首先:循环并行工作,我们只是看不到
打印。返回的
NULL
不是
print
函数的结果,而是来自并行调用的函数返回值列表。收集值并返回,而不是打印
。打印到外部文件也可以,但我建议先从普通方式开始,因为
parlappy
以一种方便的方式整理返回值

作为如何使用返回值的示例,请尝试以下操作:

library(parallel)

rows <- seq(1,9,1)

for_test <- function(i){
  txt <- NULL
  for (s in 1:3){
    txt <- rbind(txt, c(i, s, i*s))
  }
  txt
}

cls <- makeCluster(length(rows))
parLapply(cls, rows, for_test)
stopCluster(cls)

感谢您提供了这个完整的示例,我想我已经开始明白为什么我试图并行运行的实际代码不能工作了。这是否意味着当并行运行时,我不能在for循环中运行函数,并将这些输出保存到磁盘?我需要整理循环每次迭代的输出,并将它们保存在循环外部?问题是
打印
而不是
for
循环。(1) 您可以将输出保存到光盘,但(afaik)不能打印到控制台。(2) 这些函数只需返回结果,
parlappy
即可方便地为您整理结果。
library(parallel)

rows <- seq(1,9,1)

for_test <- function(i){
  txt <- NULL
  for (s in 1:3){
    txt <- rbind(txt, c(i, s, i*s))
  }
  txt
}

cls <- makeCluster(length(rows))
parLapply(cls, rows, for_test)
stopCluster(cls)
> x <- print(2)
[1] 2
> x
[1] 2
> 
> x <- for (i in 1:2) print(2 * i)
[1] 2
[1] 4
> x
NULL
>