问题描述
在sapply
和replicate
的文档中,有关于使用...
In the documentation of sapply
and replicate
there is a warning regarding using ...
现在,我可以接受它,但是我想了解它背后的原因.因此,我创建了这个小巧的示例:
Now, I can accept it as such, but would like to understand what is behind it. So I've created this little contrived example:
innerfunction<-function(x, extrapar1=0, extrapar2=extrapar1)
{
cat("x:", x, ", xp1:", extrapar1, ", xp2:", extrapar2, "\n")
}
middlefunction<-function(x,...)
{
innerfunction(x,...)
}
outerfunction<-function(x, ...)
{
cat("Run middle function:\n")
replicate(2, middlefunction(x,...))
cat("Run inner function:\n")
replicate(2, innerfunction(x,...))
}
outerfunction(1,2,3)
outerfunction(1,extrapar1=2,3)
outerfunction(1,extrapar1=2,extrapar2=3)
也许我做了一些显而易见的可怕错误,但是我却发现了这种不愉快的结果.因此,谁能向我解释为什么在以上所有对outerfunction
的调用中,我得到以下输出:
Perhaps I've done something obvious horribly wrong, but I find the result of this rather upsetting. So can anyone explain to me why, in all of the above calls to outerfunction
, I get this output:
Run middle function:
x: 1 , xp1: 0 , xp2: 0
x: 1 , xp1: 0 , xp2: 0
Run inner function:
x: 1 , xp1: 0 , xp2: 0
x: 1 , xp1: 0 , xp2: 0
就像我说的那样:文档似乎对此有所警告,但我不明白为什么会这样.
Like I said: the docs seem to warn for this, but I do not see why this is so.
推荐答案
?replicate
明确告诉我们,您尝试执行的操作无效,并且将不起作用.在?replicate
的Note
部分中,我们有:
?replicate
, in the Examples section, tells us explicitly that what you are trying to do does not and will not work. In the Note
section of ?replicate
we have:
If ‘expr’ is a function call, be aware of assumptions about where
it is evaluated, and in particular what ‘...’ might refer to. You
can pass additional named arguments to a function call as
additional named arguments to ‘replicate’: see ‘Examples’.
如果我们看示例,就会看到:
And if we look at Examples, we see:
## use of replicate() with parameters:
foo <- function(x=1, y=2) c(x,y)
# does not work: bar <- function(n, ...) replicate(n, foo(...))
bar <- function(n, x) replicate(n, foo(x=x))
bar(5, x=3)
我对文档的了解是,它们所做的远远不只是警告您在replicate()
调用中使用...
;他们明确证明它不起作用.该帮助文件中的许多讨论都与其他功能的...
参数有关,而不一定与replicate()
有关.
My reading of the docs is that they do far more than warn you about using ...
in replicate()
calls; they explicitly document that it does not work. Much of the discussion in that help file relates to the ...
argument of the other functions, not necessarily to replicate()
.
这篇关于使用"..."和“复制"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!