不幸的是,{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 (v1.0.0) 于 2021-03-01 创建