将参数传递给R中的被调用函数的问题
语境:我想使用的功能(来电者调用其他功能()被调用者)。每个被调用函数都使用一组参数,这些参数可以从一个函数到另一个函数不同。
问题:似乎我必须在调用者函数中使用参数才能将它们传递给被调用者函数(请参见fun_d下面的示例)。
问题:如何使用省略号来避免在调用函数中使用显式参数?
在嵌套函数中使用省略号和在不使用参数时运行具有多个参数的函数似乎没有回答这个问题(或者我理解不正确)。
代表:
# fun_a and fun_b have the same set of argument but do not do the same things with them
fun_a <- function(x, y, ...){x+y}
fun_b <- function(x, y, ...){x-y}
# I would like to use fun_a and fun_b in another function (fun_c) AND, have the possibility to
# give different values for each argument of fun_a and fun_b (ex: y1 and y2)
# I thought I could use the ellipsis like in fun_c:
fun_c <- function(...){
fa <- fun_a(x = x, y = y1)
fb <- fun_b(x = x, y = y2)
paste(fa, fb)
}
# fun_d works but I you like to understand why func_c does not
fun_d <- function(x, y1, y2, ...){
fa <- fun_a(x = x, y = y1)
fb <- fun_b(x = x, y = y2)
paste(fa, fb)
}
mapply(FUN = fun_c, x = c(1, 2, 3), y1 = c(1, 2, 3), y2 = c(0, 0, 0)) # not working, it says "x" is missing (and I suppose "y" too)
#> Error in fun_a(x = x, y = y1): object 'x' not found
mapply(FUN = fun_d, x = c(1, 2, 3), y1 = c(1, 2, 3), y2 = c(0, 0, 0)) # working
#> [1] "2 1" "4 2" "6 3"
由reprex 包( v2.0.0 )于 2021 年 6 月 23 日创建
回答
... 允许函数的调用者将任意参数传递给函数。
但它并没有创造相应的函数内部参数变量。如果您想使用通过...函数内部传递的参数,您有以下选择:
- 您可以
...按原样传递。例如:print_two_vectors = function (x, y, ...) { print(x, ...) print(y, ...) }print_two_vectors = function (x, y, ...) { print(x, ...) pr
print_two_vectors(pi, exp(1), digits = 2L)
print_two_vectors(pi, exp(1), digits = 2L)
int(y, ...)
}
这可用于将任意参数传递给常规print函数:
这应该是最常用的.... 对于大多数其他目的,您应该接受常规参数。
- 您可以通过访问它们
..1,..2等...elt(n)给你ñ个参数。要了解传递了example = function (...) { message('Got ', ...length(), ' arguments. The first two are: ', toString(c(..1, ..2))) message('The last one is: ', toString(...elt(...length()))) }example = function (...) { message('Got ', ...length(), ' arguments. The first two are: ', toString(c(..1, ..2))) message('The last one is: ', toString(...elt(...length()))) }多少参数,您可以使用
...length():下面是输出的样子:
example(1, 2, 3, 4) - 您可以将它们解压缩到列表中。严格来说,这与 (1) 相同,即您只是传递
...给list函数。这允许您通过 name访问元素,因为可以命名列表:add_xy = function (...) { args = list(...) args$x + args$y }add_xy(x = 1, y = 2)[1] 3.1 [1] 2.7……好吧,那个例子有点没用。但是您可以使用相同的方法来解决您的问题。
- 您可以在未评估的
...上下文中访问 的值。这是一个高级话题。它在 R 的“常规”使用中并不常用,但在元编程中使用非标准评估时它变得强大。add_xy2 = function (...) { call = match.call() eval.parent(call$x) + eval.parent(call$y) }add_xy2(x = 1, y = 2)