Check if an Object of the Specified Name is Defined or not in R Programming – exists() Function
Last Updated :
11 Apr, 2023
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
exists ( "cos" )
exists ( "diff" )
exists ( "Hello" )
|
Output:
[1] TRUE
[1] TRUE
[1] FALSE
Example 2: Apply exists() Function to Vector
R
Hello <- c (1, 2, 3, 4, 5)
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
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
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
x <- 6
if ( exists ( "x" )) {
print ( "Object 'x' exists!" )
} else {
print ( "Object 'x' does not exist!" )
}
if ( exists ( "y" )) {
print ( "Object 'y' exists!" )
} else {
print ( "Object 'y' does not exist!" )
}
|
output :
[1] "Object 'x' exists!"
[1] "Object 'y' exists!"
Share your thoughts in the comments
Please Login to comment...