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

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

问题描述

我对什么是用R中的可选参数编​​写函数的正确方法感兴趣。
随着时间的推移,我偶然发现了几条代码,它们在这里采用不同的路线,而且我不能在这个主题上找到一个适当的(官方)立场。



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

  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 ,那么函数会添加这两个数字。



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

  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

我个人更喜欢第一个版本。不过,我可以看到两者都有好有坏。第一个版本不太容易出错,但第二个版本可以用来合并任意数量的option。



是否有正确的方式来指定R中的可选参数?到目前为止,我已经解决了第一种方法,但两者偶尔都会感觉有点黑客。 解决方案

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

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

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


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

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.

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.

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".

解决方案

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

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

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