Johannes
Johannes

Reputation: 1064

Either/Or-Arguments in R functions

I am still new in writing function in R.

I try to write a function that requires: EITHER an argument "a", OR arguments "b" and "c" together.

Additionally this function has some arguments with default values.

How can I handle the either/or- arguments best. If "a" is provided I don't need "b" and "c" and vice versa, but at least one is needed.

Furthermore "a" is a string (fruits like "Apple", "Pear" etc.) , while "b" and "c" are values. There is dataframe in the background where for each fruit the value "b" and "c" are defined. So using the function would either need a valid fruit (argument "a") or the values "b" and "c" itself.

The function I started with:

f <- function(a,b,c,d=1,e=2)

Upvotes: 2

Views: 3709

Answers (3)

IRTFM
IRTFM

Reputation: 263352

 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() : 

I think there might be some untested edge cases, but it's really the questioner's responsibility to provide proper testing materials and @Johannes didn't even provide a simple test data structure much less a set of edge cases.

Upvotes: 3

Tommy
Tommy

Reputation: 40821

The missing function should help:

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

Upvotes: 1

mdsumner
mdsumner

Reputation: 29487

Check out the definition here of polar() for a good though simpler example:

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

Upvotes: 0

Related Questions