繁体   English   中英

R函数中的一个或一个或多个参数

[英]Either/Or-Arguments in R functions

我仍然是R语言中编写函数的新手。

我尝试编写一个需要以下功能的函数:将参数“ a”,或参数“ b”和“ c”放在一起。

此外,此函数还具有一些带有默认值的参数。

我如何最好地处理“或”或“或”参数。 如果提供“ a”,则不需要“ b”和“ c”,反之亦然,但至少需要一个。

此外,“ a”是字符串(诸如“ Apple”,“ Pear”等水果),而“ b”和“ c”是值。 后台有一个数据框,其中为每个水果定义了值“ b”和“ c”。 因此,使用该函数将需要有效的结果(参数“ a”)或值“ b”和“ c”本身。

我开始使用的功能:

f <- function(a,b,c,d=1,e=2)
 dfrm <- data.frame(a=LETTERS[1:3], 
        b=letters[1:3], 
        c=letters[5:7], 
        res=c("one", "two", "three") )
 dfrm
#
  a b c   res
1 A a e   one
2 B b f   two
3 C c g three

 f <- function(a=NA,b=NA,c=NA,d=1,e=2){ 
                if ( is.na(a) & (is.na(b) | is.na(c) ) ) {stop()}
                if (!is.na(a) ) { dfrm[dfrm[[1]]==a, ] 
                       # returns rows where 1st col equals `a`-value
                                   } else {
                                     dfrm[ dfrm[[2]]==b & dfrm[[3]] == c , ]
                       #returns rows where 2nd and 3rd cols match `b` and `c` vals
                                           }
 }
 f("A")
#
  a b c res
1 A a e one

 f(b="a", c="e")
#
  a b c res
1 A a e one

 f()
#Error in f() : 

我认为可能存在一些未经测试的边缘案例,但是提供适当的测试材料确实是发问者的责任,@ Johannes甚至没有提供简单的测试数据结构,更不用说提供一组边缘案例了。

missing功能应有助于:

f <- function(a,b,c,d=1,e=2) {
     if (missing(a)) {
         # use b and c
         b+c # you'll get an error here if b or c wasn't specified
     } else {
         # use a
         nchar(a)
     }
}

f('foo')    # 3
f(b=2, c=4) # 6
f(d=3)      # Error in b + c : 'b' is missing

在此处查看polar()的定义,以获取一个好而简单的示例:

http://blog.moertel.com/articles/2006/01/20/wondrous-oddities-rs-function-call-semantics

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM