【问题标题】:Passing vector elements to call as consecutive arguments传递向量元素作为连续参数调用
【发布时间】:2018-11-23 22:36:42
【问题描述】:

给定函数和测试向量:

multiply_stuff <- function(...) {
    arguments <- list(...)
    Reduce(f = `*`, x = arguments)
}

test_vec <- c(1, 20, 3, 40, 5, 60)

我想创建一个未评估的call,自动列出传递向量的所有参数。在这个例子中,这相当于表达式:

call("multiply_stuff",
     test_vec[1],
     test_vec[2],
     test_vec[3],
     test_vec[4],
     test_vec[5],
     test_vec[6])

尝试

以向量为例:

test_vec_B <- c(1, 5, 6, 8, 9, 11, 12, 14, 20, 11)

我想自动列出call("multiply_stuff",...) 中的所有test_vec_B 参数。这自然是行不通的:

call("multiply_stuff", test_vec_B)
call("multiply_stuff", list(test_vec_B))

期望的结果

未计算的表达式等价于:

call(
    "multiply_stuff",
    test_vec_B[1],
    test_vec_B[2],
    test_vec_B[3],
    test_vec_B[4],
    test_vec_B[5],
    test_vec_B[6],
    test_vec_B[7],
    test_vec_B[8],
    test_vec_B[9],
    test_vec_B[10]
)

【问题讨论】:

  • 可能相关但没有确凿的答案:stackoverflow.com/questions/42398790/…
  • @LAP 感谢您的链接。实际上do.call 提供了类似的东西,因为它可以为其args 获取一个列表。这表示我正在寻找创建一个未评估的表达式并 do.call 评估。

标签: r function functional-programming call


【解决方案1】:

您可以创建一个call 对象,然后为其添加参数:

multiply_stuff <- function(...) {
  arguments <- list(...)
  Reduce(f = `*`, x = arguments)
}
test_vec_B <- c(1, 5, 6, 8, 9, 11, 12, 14, 20, 11)

get_call <- function(f, arg_vector){
  my_call <- call(f)
  my_call[2:(length(arg_vector) + 1)] <- arg_vector
  return(my_call)
}

multiply_stuff(1, 5, 6, 8, 9, 11, 12, 14, 20, 11)
[1] 878169600

test_call <- get_call("multiply_stuff", test_vec_B)
eval(test_call)
[1] 878169600

说明:当您创建call 对象时,您可以像往常一样通过索引访问/修改函数及其参数。索引 1 是函数调用,从 2 开始的索引是参数。运行验证:

test_call2 <- call("sum", 1, 2)
test_call2[1]
test_call2[2]
test_call2[3]
eval(test_call2)

test_call2[3] <- 1234
eval(test_call2)

【讨论】:

  • 非常感谢,这是一个很好的解决方案。我认为my_call[2:(length(arg_vector) + 1)] 是这里的关键。
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 2017-04-09
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多