当参数具有默认值时,如何在递归调用中让missing()参数也丢失?
我的R函数使用丢失()
在指定输入数据的两种替代方法之间切换。但是,如果输入是factor
,我想自动将功能应用于因子级别,因此我进行递归调用。现在,我有一个问题,我将所有参数转发到递归调用中,因此没有任何参数不再丢失了!如何使用父呼叫中缺少的所有参数进行递归调用?
最小示例:
f <- function(a, b = 1){
print(missing(b))
if(length(a)>0) f(a = a[-1], b = b)
}
f(1:2)
prints:
[1] TRUE
[1] FALSE
[1] FALSE
我想要的是
[1] TRUE
[1] TRUE
[1] TRUE
当b没有默认值时,这是有效的,因此f
当然
f <- function(a, b){
...
也可以选择使用切换递归调用,如果(缺少(b))
if(missing(b)) f(a = a[-1]) else f(a = a[-1], b = b)
...但是这对于多个参数变得复杂,也剥夺了我在r ;--中学习有关参数奇怪奇迹的选择。 )
My R function uses missing()
to switch between two alternative ways of specifying input data. However, if the input is a factor
, I want to automatically apply the function on the factor levels instead, so I make a recursive call. Now I have the problem that I forward all arguments to the recursive call, so none of the parameters are missing anymore! How do I make a recursive call with all the parameters missing that are also missing in the parent call?
Minimal example:
f <- function(a, b = 1){
print(missing(b))
if(length(a)>0) f(a = a[-1], b = b)
}
f(1:2)
prints:
[1] TRUE
[1] FALSE
[1] FALSE
What I want is
[1] TRUE
[1] TRUE
[1] TRUE
This works when b has no default value, so f
is instead
f <- function(a, b){
...
Also of course I have the option to switch the recursive call using if(missing(b))
if(missing(b)) f(a = a[-1]) else f(a = a[-1], b = b)
... but this gets complicated for multiple parameters and also deprives me of the option to learn something about the strange wonders of parameter handling in R ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
match.call
捕获呼叫,然后在呼叫中替换a
a [-1]
。然后,使用do.call
,而不是使用参数调用该函数,它将仅在递归调用中提供最初放入函数的参数。You can capture the call with
match.call
, and substitutea
fora[-1]
in the call. Then instead of calling the function with arguments, usedo.call
, which will only supply the arguments initially put into the function in the recursive calls.