Check if an Object of the Specified Name is Defined or not in R Programming – exists() Function
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
Example :
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
# Define a variable 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' exists!"
Please Login to comment...