简体   繁体   English

为什么在使用嵌套函数时,省略号(…)匹配更多的参数?

[英]Why does R ellipsis (…) match more arguments when using nested functions?

I would like to understand why the ... argument matches the extra argument when nesting f() within g() . 我想了解为什么在g()嵌套f()...参数匹配extra参数。

Say that f() is this function: 假设f()是此函数:

f <- function(..., extra = NULL) {
    . <- list(...)
    print(.)
}

The output is, as expected, what is contained in the ... argument: 正如预期的那样,输出是...参数中包含的内容:

f("a", "b", "c", extra = "123")

# [[1]]
# [1] "a"

# [[2]]
# [1] "b"

# [[3]]
# [1] "c"

However, when using it within another function, say g() : 但是,在另一个函数中使用它时,说g()

g <- function(..., extra = NULL) {
    f(..., extra)
}

The ... also captures the extra argument: ...还捕获了extra参数:

g("a", "b", "c", extra = "123")

# [[1]]
# [1] "a"

# [[2]]
# [1] "b"

# [[3]]
# [1] "c"

# [[4]]
# [1] "123"

My question is twofold: (1) why is this the case and (2) how to correctly handle this? 我的问题有两个:(1)为什么会这样(2)如何正确处理呢?

In f() you define and set an argument called extra, that is never used, thus it doesnt appear anywhere. f()您定义并设置了一个名为extra的参数,该参数从未使用过,因此它不会出现在任何地方。 The f(..., extra) in g() captures all the arguments in g and assigns them to ... in f() . g()f(..., extra)捕获g()所有参数,并将它们分配给f() ... The extra in g(..., extra) has nothing to do with the extra in f(..., extra = NULL) . g(..., extra)中的extra与f(..., extra = NULL)的extra没有关系。 They have the same names but live in different environments - the environments of g() and f() respectively. 它们具有相同的名称,但是生活在不同的环境中-分别是g()f()的环境。 To achieve the same behaviour assign the g() 's extra to f() 's extra in the function call: 要实现相同的行为,请在函数调用中将g()的额外值分配给f()的额外值:

g1 <- function(..., extra = NULL) {
    f(..., extra = extra)
}
> g1("a", "b", "c", extra = NULL)
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM