“正确"在 R 函数中指定可选参数的方法 [英] "Correct" way to specifiy optional arguments in R functions

查看:26
本文介绍了“正确"在 R 函数中指定可选参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 R 中编写带有可选参数的函数的正确"方法是什么感兴趣.随着时间的推移,我在这里偶然发现了几段走不同路线的代码,我找不到关于这个主题的合适(官方)立场.

I am interested in what is the "correct" way to write functions with optional arguments in R. Over time, I stumbled upon a few pieces of code that take a different route here, and I couldn't find a proper (official) position on this topic.

到目前为止,我已经编写了这样的可选参数:

Up until now, I have written optional arguments like this:

fooBar <- function(x,y=NULL){
  if(!is.null(y)) x <- x+y
  return(x)
}
fooBar(3) # 3
fooBar(3,1.5) # 4.5

如果只提供了 x,该函数只返回它的参数.它对第二个参数使用默认的 NULL 值,如果该参数恰好不是 NULL,则该函数将两个数字相加.

The function simply returns its argument if only x is supplied. It uses a default NULL value for the second argument and if that argument happens to be not NULL, then the function adds the two numbers.

或者,您可以编写这样的函数(其中第二个参数需要通过名称指定,但也可以 unlist(z) 或定义 z <- sum(...) 代替):

Alternatively, one could write the function like this (where the second argument needs to be specified by name, but one could also unlist(z) or define z <- sum(...) instead):

fooBar <- function(x,...){
  z <- list(...)
  if(!is.null(z$y)) x <- x+z$y
  return(x)
}
fooBar(3) # 3
fooBar(3,y=1.5) # 4.5

我个人更喜欢第一个版本.但是,我可以看到两者的好与坏.第一个版本不太容易出错,但第二个版本可用于合并任意数量的选项.

Personally I prefer the first version. However, I can see good and bad with both. The first version is a little less prone to error, but the second one could be used to incorporate an arbitrary number of optionals.

在 R 中是否有一种正确"的方式来指定可选参数?到目前为止,我已经确定了第一种方法,但两者都会偶尔感觉有点hacky".​​

Is there a "correct" way to specify optional arguments in R? So far, I have settled on the first approach, but both can occasionally feel a bit "hacky".

推荐答案

您也可以使用 missing() 来测试是否提供了参数 y:

You could also use missing() to test whether or not the argument y was supplied:

fooBar <- function(x,y){
    if(missing(y)) {
        x
    } else {
        x + y
    }
}

fooBar(3,1.5)
# [1] 4.5
fooBar(3)
# [1] 3

这篇关于“正确"在 R 函数中指定可选参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆