代码之家  ›  专栏  ›  技术社区  ›  stevec Zxeenu

将参数传递给callr::r()后台进程并在中访问它们?

  •  0
  • stevec Zxeenu  · 技术社区  · 3 年前

    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() 并且这些论点可以在后台过程中访问?

    1 回复  |  直到 3 年前
        1
  •  1
  •   stevec Zxeenu    3 年前

    你必须把论点移到里面 二者都 args和内部函数()的列表,如下所示:

    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
    

    来源: here