当参数具有默认值时,如何在递归调用中让missing()参数也丢失?

发布于 2025-01-17 15:18:46 字数 868 浏览 2 评论 0原文

我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

您的好友蓝忘机已上羡 2025-01-24 15:18:46

您可以使用match.call捕获呼叫,然后在呼叫中替换a a [-1]。然后,使用do.call,而不是使用参数调用该函数,它将仅在递归调用中提供最初放入函数的参数。

f <- function(a, b = 1){
  print(missing(b))
  
  call_list <- as.list(match.call())[-1]

  if(length(a) > 0) {
    a <- a[-1]
    call_list$a <- a
    do.call(f, call_list)
  }
}

f(1:2)
#> [1] TRUE
#> [1] TRUE
#> [1] TRUE

You can capture the call with match.call, and substitute a for a[-1] in the call. Then instead of calling the function with arguments, use do.call, which will only supply the arguments initially put into the function in the recursive calls.

f <- function(a, b = 1){
  print(missing(b))
  
  call_list <- as.list(match.call())[-1]

  if(length(a) > 0) {
    a <- a[-1]
    call_list$a <- a
    do.call(f, call_list)
  }
}

f(1:2)
#> [1] TRUE
#> [1] TRUE
#> [1] TRUE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文