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.
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"
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With