In R, you can check if a variable exists using the exists() function. This function tests whether an object (like a variable) exists in the current environment or in a specified environment.
Syntax
exists(name)
Parameters
name: It is the name of the object to check for existence.
Return value
It returns a logical value TRUE if the object exists and FALSE otherwise.
Example 1: Basic usage
string <- "Hello"
exists("string")
exists("log")
exists("World")
Output
[1] TRUE
[1] TRUE
[1] FALSE
Example 2: Checking if a vector exists
vec <- c(1, 3, 3, 4)
exists("vec")
Output
[1] TRUE
Example 3: Checking if a data frame exists
df <- data.frame(
col1 = c(1, 2, 3),
col2 = c(4, 5, 6)
)
exists("df")
Output
[1] TRUE
Example 4: Checking if a function exists
Let’s check the existence of rbind.fill() function from the plyr package. It will return FALSE because the rbind.fill() is not a built-in function; it is a library function.
exists("rbind.fill")
Output
[1] FALSE
To use this function, we have to import the library first.
library("plyr")
exists("rbind.fill")
Output
TRUE
Example 5: Checking if an object exists in a specific environment
var <- 1
env <- new.env()
env$var <- 21
exists("var", where = env)
exists("var", where = globalenv())
Output
[1] TRUE
[1] TRUE
You can see that the exists() function only checks for the existence of an object and not for its value. So, it will return TRUE even if the object has a value of NULL.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.