In this R tutorial, I’ll show you how to check whether a data object exists in your R programming environment. The tutorial is mainly relying on the usage of the exists R function. Let’s start with the basic R syntax and the definition of the exists function:

Basic R Syntax:

exists(x)

exists(x)

Definition:

The exists function checks whether an R object is defined in the R environment.

The exists function is very flexible and can be applied to different R objects such as vectors, variables of a data.frame, or functions. In the following article, I’m going to show you four examples for the usage of exists.

Let’s dive into it!

Example 1: Apply exists() Function to Vector

Probably the easiest and most intuitive way to apply the exists function is when we use it for vectors. Let’s create a simple vector for our first example:

x <- c(2, 9, 5, 3)# Create example vector

x <- c(2, 9, 5, 3) # Create example vector

And not let’s use exists() to check if this vector is properly defined in our R environment:

exists("x")# Apply exists function to vector# TRUE

exists("x") # Apply exists function to vector
# TRUE

The exists function returns TRUE to the RStudio console. In other words: Yes, the vector x exists.

For comparison, let’s also apply the exists function to a vector that we did not define before:

exists("y")# Apply exists function to non-existent vector# FALSE

exists("y") # Apply exists function to non-existent vector
# FALSE

The exists command returns FALSE, i.e. the vector y does not exist.

That’s it! With this simple code we can check the existence of any data element we want.

However, when we want to check for the existence of variables in a data.frame, it get’s slightly more difficult. But that’s what I’m going to show you in the next example.