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
You could consider testing existence of variables through their character symbols. Pass
variables-to-check
as character vector and passvariables-in-existence
as characters usingls()
A modification to the function lets you return only existing-variables