Open In App

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

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Example 1: Apply exists() Function to variable

In this example, we will use the exists() function to check if various objects are defined

R
# Calling exists() function
exists("cos")
exists("diff")
exists("Hello")

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

In the output, the exists() function returns TRUE for predefined functions like cos and diff, while it returns FALSE for Hello, as it hasn’t been defined yet.

Example 2: Checking for User-defined Objects (Vectors)

We will declare a vector and see if it exists or not using the exists() function.

R
# Creating a vector
Hello <- c(1, 2, 3, 4, 5)

# Calling exists() function
exists("Hello")

Output
[1] TRUE

Here, when defining the vector Hello, the exists() function gives TRUE, which verifies that the object has been defined.

Example 3: Checking if a Variable Exists in a Data Frame

You can also verify whether a variable exists in a data frame or any other R object using exists().

R
# creating a data frame
friend.data <- data.frame(
    friend_id = c(1:5),
    friend_name = c("Sachin", "Sourav",
                    "Dravid", "Sehwag",
                    "Dhoni"),
    stringsAsFactors = FALSE
)
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
[1] TRUE

In this example, exists(‘friend_id’) returns TRUE because the variable friend_id is part of the friend.data data frame.

Example 4: Conditional Check for Object Existence

The exists() function in R can be used to check if an object with a specified name exists in the current environment or not. The example of how to use the exists() function.

R
x <- 6

# Check if an object 'x' exists
if (exists("x")) {
  print("Object 'x' exists!")
} else {
  print("Object 'x' does not exist!")
}

# Check if an object 'y' exists
if (exists("y")) {
  print("Object 'y' exists!")
} else {
  print("Object 'y' does not exist!")
}

Output
[1] "Object 'x' exists!"
[1] "Object 'y' does not exist!"

Related Article:



Next Article

Similar Reads