【问题标题】:How to make parallel processing in R with empty result?如何在 R 中进行并行处理,结果为空?
【发布时间】:2019-04-03 08:45:08
【问题描述】:

我想通过使用包“doParallel”和“foreach”在 R 中进行并行处理。而且,这个想法是只进行并行计算而没有任何结果。我发现看起来像“foreach”运算符总是返回某种在 RAM 中占用内存的结果。因此,我需要任何帮助才能获得并行处理循环的空结果。

# 1. Packages
library(doParallel)
library(foreach)

# 2. Create and run app cluster
cluster_app <- makeCluster(detectCores())
registerDoParallel(cluster_app)

# 3. Loop with result
list_i <- foreach(i = 1:100) %dopar% {
  print(i)
}

# 4. List is not empty
list_i

# 5. How make loop with empty 'list_i' ?
# TODO: make 'list' equal NULL or NA

# 6. Stop app cluster
stopCluster(cluster_app)

【问题讨论】:

  • 也许这个return(NULL)
  • 如果您真的想返回“无”,请使用.combine = 'c'
  • 这两个假设都不成立。所有 100 个元素的第一个设置“NULL”值。第二个来自作为 100 个数字的结果列表。这里的问题是得到一个值作为结果 - NA 或 NULL。
  • print(x) 实际上返回 x 不可见,例如y &lt;- print(42) 将 42 分配给 y。因此,正如上面所建议的,y &lt;- foreach(x = 1:3, .combine = c) %dopar% { ... ; NULL } 将返回 NULL。仅供参考,根据经验,您可以像想到 lapply() 一样想到 foreach() - 也就是说 - 您想使用它们来返回值。很少有人只因为它们的副作用而想要它们。此外,不要假设元素的处理顺序。

标签: r foreach parallel-processing doparallel


【解决方案1】:

这是我找到的解决方案:

# 1. Packages
library(doParallel)
library(foreach)

# 2. Create and run app cluster
cluster_app <- makeCluster(detectCores())
registerDoParallel(cluster_app)

# 3. Loop with result
list_i <- foreach(i = 1:100) %dopar% {
  print(i)
}

list_i

# 4. Mock data processing
mock_data <- function(x) {
  data.frame(matrix(NA, nrow = x, ncol = x))
}

# 4. How make loop with empty 'list_i' ?
foreach(i = 1:10, .combine = 'c') %dopar% {

  # 1. Calculations
  mock_data(x)

  # 2. Result
  NULL
}

# The results has only one value 'NULL' (not a data set)
list_i


# 5. Stop app cluster
stopCluster(cluster_app)

【讨论】:

  • 我想你明白了,但你最好为结果为空的情况提供相同的示例循环。我还让您注意print(i) 不会在使用 %dopar% 的循环中打印任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2015-02-13
  • 2019-08-16
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多