Reputation: 175
If I have a function with argument (...) and want to check if a variable is defined in the argument. How can I do this? I have already looked at the solution provided at this link: How to check if object (variable) is defined in R?. However, it does not solve my problem.
# Scenario 1
exists("a")
# [1] FALSE
# Scenario 2
a <- 10
exists("a")
# [1] TRUE
# Define a function for remaining scenarios
f = function(...){exists("a", inherits = F)}
# Scenario 3
f()
# [1] FALSE
# Scenario 4
a <- 10
f()
# [1] FALSE
# Scenario 5
a <- 10
f(a = 5)
# [1] FALSE
I want the answer to be TRUE
in Scenario 5.
Upvotes: 1
Views: 496
Reputation: 206167
Generally you use ...
when you are passing parameters to other functions, not when you are using them in the function itself. It also makes a difference if you want to evaluate the parameter value or if you want to leave it unevaulated. If you need the latter, then you can do something like
f = function(...) {
mc <- match.call(expand.dots = TRUE)
"a" %in% names(mc)
}
This will return true for both
f(a = 4)
f(a = foo)
even when foo
doesn't exist.
Upvotes: 3
Reputation: 12451
Does this suffice?
# Define a function for remaining scenarios
f = function(...){"a" %in% names(list(...))}
# Scenario 3
f()
# [1] FALSE
# Scenario 4
a <- 10
f()
# [1] FALSE
# Scenario 5
f(a = 5)
# [1] FALSE
f(a = 5)
[1] TRUE
Upvotes: 3