Skip to content
Related Articles

Related Articles

Check if an Object of the Specified Name is Defined or not in R Programming – exists() Function

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Oct, 2021

exists() function in R Programming Language is used to check if an object with the names specified in the argument of the function is defined or not. It returns TRUE if the object is found.

Syntax: exists(name)

Parameters: 

  • name: Name of the Object to be searched

exists() Function in R Language Example

Example 1: Apply exists() Function to variable

R




# R program to check if
# an Object is defined or not
 
# Calling exists() function
exists("cos")
exists("diff")
exists("Hello")

Output: 

[1] TRUE
[1] TRUE
[1] FALSE

Example 2:  Apply exists() Function to Vector

R




# R program to check if
# an Object is defined or not
 
# Creating a vector
Hello <- c(1, 2, 3, 4, 5)
 
# Calling exists() function
exists("Hello")

Output: 

[1] TRUE

In the above examples, it can be seen that when there was no object named “Hello” defined in the first code, the exists() function returned FALSE, whereas after the declaration of the “Hello” Object, the exists() function returned TRUE. This means that the exists() function checks for pre-defined and user-defined, objects.

Example 3: Check if Variable in Data Frame is Defined

R




# R program to create dataframe
# and apply exists function
 
# creating a data frame
friend.data <- data.frame(
    friend_id = c(1:5),
    friend_name = c("Sachin", "Sourav",
                    "Dravid", "Sehwag",
                    "Dhoni"),
    stringsAsFactors = FALSE
)
# print the data frame
print(friend.data)
 
attach(friend.data)
exists('friend_id')

Output:

  friend_id friend_name
1         1      Sachin
2         2      Sourav
3         3      Dravid
4         4      Sehwag
5         5       Dhoni
TRUE

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!