在 R 中,如何在调用函数中评估 ... ?
如果我想知道 R 函数中 ...
参数中存储的内容,我可以简单地将其转换为列表,就像这样
foo <- function(...)
{
dots <- list(...)
print(dots)
}
foo(x = 1, 2, "three")
#$x
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] "three"
我不知道如何评估 < code>... 在调用函数中。在下一个示例中,我希望 baz 的内容将 ...
参数返回给 bar
。
bar <- function(...)
{
baz()
}
baz <- function()
{
# What should dots be assigned as?
# I tried
# dots <- get("...", envir = parent.frame())
# and variations of
# dots <- eval(list(...), envir = parent.frame())
print(dots)
}
bar(x = 1, 2, "three")
get("...", envir = Parent.frame())
返回 <...>
,看起来很有希望,但我不明白如何从中提取有用的东西。
eval(list(...), envir = Parent.frame())
抛出错误,声称 ...
使用不正确。
如何从 bar
检索 ...
?
If I want to know what is stored in a ...
argument within an R function, I can simply convert it to be a list, like so
foo <- function(...)
{
dots <- list(...)
print(dots)
}
foo(x = 1, 2, "three")
#$x
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] "three"
What I can't figure out is how to evaluate ...
in the calling function. In this next example I want the contents of baz
to return the ...
argument to bar
.
bar <- function(...)
{
baz()
}
baz <- function()
{
# What should dots be assigned as?
# I tried
# dots <- get("...", envir = parent.frame())
# and variations of
# dots <- eval(list(...), envir = parent.frame())
print(dots)
}
bar(x = 1, 2, "three")
get("...", envir = parent.frame())
returns <...>
, which looks promising, but I can't figure out how to extract anything useful from it.
eval(list(...), envir = parent.frame())
throws an error, claiming that ...
is used incorrectly.
How can I retrieve the ...
from bar
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一句话:不要。尝试重新定义 R 的范围规则很可能最终会带来心痛和痛苦。
In a word: don't. Trying to redefine R's scoping rules is only likely to end up in heartache and pain.
想通了。我需要
eval
和substitute
的组合。baz
应定义为Figured it out. I needed a combination of
eval
andsubstitute
.baz
should be defined as这应该可行:
只需在子函数中分配它即可。
或者,您可以将省略号指定为父函数中的列表:
这是相同的想法,但我不建议这样做,因为您要覆盖省略号:
This should work:
Just assign it in the subfunction.
Alternatively, you can assign the ellipsis as a list in the parent function:
This is the same idea, but I wouldn't suggest it because you're overwriting the ellipsis: