Check if arguments passed into a function are defined or not in r?

929 Views Asked by At

I want to know how the existence of a variable passed into a function can be checked before applying more operations on them inside the function. So that if a variable is not found, it could be ignored using an if-else statement. Here is a sample code. Note that the names of the variables are constructed using "paste0" function. This is because they have to be fed into a loop later on, which I omitted the remaining operations for the sake of simplification.

existence = function(x1, x2, x3, x4) {
  for (i in 1:4){
    varName <-paste0("x", i)
    
    # Check if a defined variable is passed into the function
    if(exists(varName)){ 
      message(varName, " is defined")
    } else {
      message(varName, " is NOT defined")
    }
  }
}

Defined variables are only b and c. The variable a is not defined. however, it is passed into the function. The "existence" function has to also print "Not defined" massage in case of passing a NULL variable into it.

b <- 10
c <- 5
existence(a, b, NULL, c)

The "exist" function I used is not giving the correct answer. I want the answer to be:

x1 is Not defined
x2 is defined
x3 is Not defined
x4 is defined
1

There are 1 best solutions below

0
On

You could consider testing existence of variables through their character symbols. Pass variables-to-check as character vector and pass variables-in-existence as characters using ls()

b <- 10
c <- 5

existence = function(vars_to_check, vars_created) {
    test <- vars_to_check %in% vars_created
    names(test) <- vars_to_check
    test
}

existence(
    c('a', 'b', 'NULL', 'c'), 
    ls()
)
#     a     b  NULL     c
# FALSE  TRUE FALSE  TRUE

A modification to the function lets you return only existing-variables

existence = function(vars_to_check, vars_created) {
    test <- vars_to_check %in% vars_created
    vars_to_check[test]
}

existence(
    c('a', 'b', 'NULL', 'c'), 
    ls()
)
# 'b' 'c'