How To Fix The Error object not found In R

The error object not found in R typically occurs when you are trying to access an object (such as a variable, function, or data frame) that doesn’t exist in your current environment.

This can happen for a variety of reasons, making R fail to resolve the reference you provide. This guide will explain how you can fix the error in each case.

How To Fix The Error object not found In R

You mistype the object’s name

There are times you mistype the name of the object you want to use. If the wrong name isn’t available, R will give you an error. This happens more in real life than you might think.

For instance, we create a data frame from the built-in dataset mtcars with the function head(). If we give the resulting data frame the name “df1” but use “df2” later, R will tell you that such an object doesn’t exist:

df1 <- head(mtcars)
df2
Error: object 'df2' not found

Make sure you have spelled the object name correctly and that you are using the correct case, which should be “df1” in the above example.

df1 <- head(mtcars)
df1

Output

You haven’t created the object

Another common scenario is when you use a name of an object that hasn’t been created.

This may happen when you read a tutorial and execute a copied code. It may contain some objects that need to be created first.

For example, in our guide on finding duplicates in R, we demonstrate the capabilities of the function duplicated() with a simple example. In it, we first create a vector called x. When you forget this step and jump to the command with duplicated() right away, it won’t work as intended:

duplicated(x)
Error in duplicated(x) : object 'x' not found

Make sure that you have created the object or imported it into your environment before trying to use it. In this case, follow our example precisely and create x first to make it work:

x <- c(1, 2, 3, 4, 3, 4, 5, 6, 7, 5, 6, 8, 9, 10)
duplicated(x)

Output

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

You haven’t imported the object

R allows you to save objects into files and load them later. This is a great way to back up your working data and make it available for other sessions.

For instance, you can save the vector x above into an RData file with the save() function:

save(x, file = "x.RData")

But remember that R doesn’t automatically load this file, and therefore the vector x. If you open a new R session and use x right away, you will see the same error:

x
Error: object 'x' not found

Use the load() function to load objects in a file to your R environment when you want to use them:

load("x.RData")
x

Output

 [1] 1 2 3 4 3 4 5 6 7 5 6 8 9 10

Summary

The error object not found in R occurs when you give it a name that doesn’t exist in its memory. You should double-check to see whether you have created, loaded, or typed the name the right way.

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *