1

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.

Rahi
  • 135
  • 1
  • 13

2 Answers2

3

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
Limey
  • 10,234
  • 2
  • 12
  • 32
3

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • ok. Got it. It just that my intention is in two steps: 1) select function based on parameters defined in ```...```. 2) Pass the parameters to the function. – Rahi Jun 09 '21 at 17:05