r - 如何将全局选择权传递给 future 的 worker ?

标签 r future

我使用 future.apply 来并行化 R 中的任务。在我的全局环境中,我设置了一个选项,该选项特定于我正在使用的包。我观察到此选项不会传递给 future.apply 使用的工作人员。

如何将我设置的选项传递给 future.apply 使用的每个工作人员?

最佳答案

不幸的是,{future} 包({future.apply} 函数所依赖的)尚不支持全局选项的传递,尽管the development team is working on it.

current workaround是重新声明在 future.lapply() 或类似函数中使用的表达式或函数内部的选项。

这是当前行为的可重现示例:

library(future.apply)

# Example data
datasets <- list(
  'Sample 1' = c(1, 2, NA_real_, 4),
  'Sample 2' = c(1, 2, 3, 4)
)

# Example option and function

  options(na_handling = 'remove')
  
  mean_fn <- function(x) {
    na_option <- getOption('na_handling')
    if (!is.null(na_option) && na_option == "remove") {
      mean(x, na.rm = TRUE)
    } else {
      mean(x, na.rm = FALSE)
    }
  }

# Use `future_lapply` like normal

  plan(multiprocess(workers = 2))
  future_lapply(X = datasets,
                FUN = mean_fn)
#> $`Sample 1`
#> [1] NA
#> 
#> $`Sample 2`
#> [1] 2.5

这是您在函数/表达式内部手动声明选项的解决方法。

# Manually pass option

  future_lapply(X = datasets,
                FUN = function(x) {
                  options(na_handling = 'remove')
                  mean_fn(x)
                })
#> $`Sample 1`
#> [1] 2.333333
#> 
#> $`Sample 2`
#> [1] 2.5

reprex package 于 2021 年 3 月 1 日创建(v1.0.0)

关于r - 如何将全局选择权传递给 future 的 worker ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63236841/

相关文章:

multithreading - 产生线程并获得 future 结果的最佳方法是什么?

asynchronous - Flutter: future 和共同偏好

r - 在ggplot2中将误差线与每组不同数量的条形图对齐

r - 从命名空间内调用特殊函数

R:xts 复杂查询

r - 构建 R 包 : Undocumented S4 classes (it is documented! )

r - 在公式中扩展因子相互作用

c++ - 在 C++11 中使用 futures、async 和 thread 实现搜索

asynchronous - 我如何 read_until future 链中的 tokio::net::TcpStream?