To check if a variable exists in R, use the exists() function.
The exists() function checks if an object with a given name exists in the current environment. It returns a logical value of TRUE if the object exists and FALSE if it does not.
exists(name, where = parent.frame(), mode = "any", inherits = TRUE)
name: It is the name of the object to check for existence.
where: It is the environment in which to look for the object.
mode: It is the type of object to check for.
inherits: It is a logical value suggesting whether to check for the object in the specified environment and its parents.
var <- 1 exists("var") exists("x")
 TRUE  FALSE
You can see that the “var” variable exists. That’s why it returns TRUE, and x does not exist and returns FALSE.
Checking if an object exists in a specific environment in R
To create a new environment in R, use the new.env() function.
An environment in R is an object that stores a collection of symbols and their values.
Use the exists() function to check if an R object exists in the specific environment.
var <- 1 env <- new.env() env$var <- 21 exists("var", where = env) exists("var", where = globalenv())
 TRUE  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.
Checking if a vector exists in R
Use the exists() function to check if a vector exists in R.
Create a vector using the c() function and then check its existence using the exists() function.
info <- c(1, 3, 3, 4) exists("info")
Let’s check a vector that does not exist.
info <- c(1, 3, 3, 4) exists("rv")
How to Check If data frame exists in R
Use the exists() function to check if a data frame exists in R.
df <- data.frame( r1 = c(11, 21, 19), r2 = c(18, 29, 46) ) exists("df")
You can see that we created a data frame variable df using the data.frame() function.
How to check if a function exists in R
You can check if a function exists using the exists() function in R.
Let’s check the existence of rbind.fill() function from the plyr package.
And it will return FALSE because the rbind.fill() is not a built-in function; it is a library function, and to use that function, we have to import the library first.
Now, it will return TRUE because we imported a library.
To check if an object exists or a variable exists in R, use the built-in exists() function. The exists() function accepts an R object and returns TRUE or FALSE based on if it exists or not.
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.