1

我有一个看起来像这样的并行过程:

library(foreach)
library(doSNOW)

cl = makeCluster(parallel::detectCores() - 1, type = "SOCK", outfile = "out.txt") 
registerDoSNOW(cl)

l = foreach(i = 1:100) %dopar% { 
  res = withCallingHandlers(
    read.csv("somefilethatdoesntexist.csv"), error = function(e) e)
  if(inherits(res, "error")) res = NULL
  res
}

我的期望是,即使“表达式”中有错误,循环也应该继续,但它会因错误而退出,并且不会创建生成的“l”变量。

这似乎尤其与丢失的文件有关。但是,如果我将它包装在 tryCatch 中并在“表达式”中进行适当处理,它怎么会出错?

4

1 回答 1

3

也许这个(改编自这里):

library(foreach)
library(doSNOW)

cl = makeCluster(parallel::detectCores() - 1, type = "SOCK", outfile = "out.txt") 
registerDoSNOW(cl)

l = foreach(i = 1:2) %dopar% { 
  withCallingHandlers({
      res <- withRestarts( read.csv("somefilethatdoesntexist.csv"),
                          skipError=function() return(NULL))
    },
    error=function(e) {saveRDS(e, paste0("E:/temp/", i, ".rds")); invokeRestart("skipError")})
  res
}

l
#[[1]]
#NULL
#
#[[2]]
#NULL

e <- readRDS("E:/temp/1.rds")
e
#<simpleError in file(file, "rt"): cannot open the connection>
于 2018-11-15T09:06:28.170 回答