Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Find variables supplied to functions with the '...' argument with exists()

Tags:

r

I want to supply an optional variable to a function, let the functions check whether this argument was supplied, and let it perform the corresponding set of computations. I thought I can use the '...' operator for that.

The simplest example I can think of (which sadly failed) is this:

monkeyfun = function(...){

     if (exists("monkey")){
       return('monkey found')
     } else {
       return('monkey not found')
     }

  }

Now monkeyfun(monkey=0) as well as monkeyfun() both return "monkey not found".

As a sanity check, defining monkey = 1 outside of the function works and returns "monkey found".

The documentation on the '...' argument doesn't really help me understand this issue and I was unable to find a formulation of this question that gives matching results on here (I do understand this question is basic and most likely discussed somewhere)...

I would really appreciate some help with this.

like image 844
Affaeng Avatar asked Mar 08 '15 01:03

Affaeng


3 Answers

I would use hasArg:

monkeyfun <- function(...) {
  if (hasArg("monkey")) {
    return('monkey found')
  } else {
    return('monkey not found')
  }
}
monkeyfun()
# [1] "monkey not found"
monkeyfun(monkey=0)
# [1] "monkey found"
like image 124
Joshua Ulrich Avatar answered Oct 23 '22 00:10

Joshua Ulrich


I would use match.call since it returns all the function arguments specified by their full names. Here How I would rewrite your function:

monkeyfun = function(...){
  params <- as.list(match.call()[-1])
  if ("monkey" %in% names(params)){  ## note how I change the test here
    return('monkey found')
  } else {
    return('monkey not found')
  }

}

# monkeyfun()
# [1] "monkey not found"
# > monkeyfun(monkey=0)
# [1] "monkey found"
like image 37
agstudy Avatar answered Oct 23 '22 01:10

agstudy


Take a look at this dialog with the R interpreter. Generally existence is tested by seeing if the length is greater than 0:

 monkeyfun = function(...){
 print(str(list(...)))
   }
 monkeyfun(monkey=0)
#List of 1
# $ monkey: num 0
#NULL
 monkeyfun = function(...){
 loclist = list(...)
  if (exists(loclist$monkey)){
        return('monkey found')
      } else {
        return('monkey not found')
      } }
 monkeyfun(monkey=0)
#Error in exists(loclist$monkey) : invalid first argument
 monkeyfun = function(...){
 loclist = list(...)
  if (length(loclist$monkey)){
        return('monkey found')
      } else {
        return('monkey not found')
      } }
 monkeyfun(monkey=0)
#[1] "monkey found"
 monkeyfun(monk_uncle=1)
#[1] "monkey not found"
like image 3
IRTFM Avatar answered Oct 23 '22 00:10

IRTFM