1

R代码可以像这样在后台进程中运行

callr::r(function(){ 2 * 2 })
# [1] 4

当我尝试这样做时,args我不知道如何访问它们。我尝试了一些明显的事情:

callr::r(function(){ 2 * 2 }, args = list(x=3))

callr::r(function(){ 2 * x }, args = list(x=3))

callr::r(function(){ 2 * args$x }, args = list(x=3))

callr::r(function(){ 
  args <- commandArgs()
  2 * args$x 
  }, 
  args = list(x=3))

# Error: callr subprocess failed: unused argument (x = base::quote(3))
# Type .Last.error.trace to see where the error occurred

我也尝试使用调试,browser()但在这种情况下它没有以通常的方式工作。

问题

如何将参数传递给调用的后台进程callr::r()并在后台进程中访问这些参数?

4

1 回答 1

1

您必须在args 列表和 function() 内部移动参数,如下所示

callr::r(function(x){ 2 * x }, args = list(x = 3))
# [1] 6

或者像这样:

x <- 3
callr::r(function(x){ 2 * x }, args = list(x))
# [1] 6

多个参数的相同想法:

x <- 3
y <- 4
z <- 5

callr::r(function(x, y, z) { 2 * x * y * z }, args = list(x, y, z))
# [1] 120

来源:这里

于 2022-01-14T07:14:36.277 回答