How to Fix in R: object not found


One common error you may encounter in R is:

Error: object 'x' not found

This error usually occurs for one of two reasons:

Reason 1: You are attempting to reference an object you have not created.

Reason 2: You are running a chunk of code where the object has not been defined in that chunk.

The following examples how to resolve this error in each of these scenarios.

Example #1: Object not found when object does not exist

Suppose we use the following code to display a data frame that we have not created:

#create data frame
my_df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                    points=c(99, 90, 86, 88, 95),
                    assists=c(33, 28, 31, 39, 34),
                    rebounds=c(30, 28, 24, 24, 28))

#attempt to display data frame
my_data

Error: object 'my_data' not found

We receive an error because the object my_data does not exist.

Instead, we need to type the correct name of the data frame that we created:

#display data frame
my_df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

This time we’re able to display the data frame without an error because we used the correct name.

Note that we can also use ls() to display all object names in our current environment and exists() to check if a specific object name exists:

#display the names of all objects in environment
ls()

[1] "df"    "my_df" "x"

#check if my_data exists
exists('my_data')

[1] FALSE

We can see that exists(‘my_data’) returns FALSE, which explains why we received an error when we attempted to display it.

Example #2: Object not found when incorrect chunk of code is highlighted

Another reason that we might receive an object not found error is because we have highlighted a chunk of code to run in RStudio that doesn’t contain the name of the object we’re attempting to reference.

For example, consider the following screenshot where we highlight rows 3 through 5 and attempt to calculate the mean of a value named x:

object not found error in R

Since we created the vector named x in row 2, we receive an error because we haven’t actually created that vector in the chunk of code that we highlighted.

If we instead make sure that we highlight the whole chunk of code we’re interested in, we won’t receive any error:

Notice that RStudio displays the mean of vector x without any errors this time.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

Leave a Reply

Your email address will not be published.