If you have never encountered an error message then you have never really written a computer program. The “object not found” error can be one of the hardest to diagnose, and yet it can be quite easy to fix. However, it is also easy to get as your programs grow and object names become more complex.
The circumstances of this error.
The “object not found” error occurs when you try to call an object name that has not been defined. This is one of the reasons why diagnosing this message can be hard. While it is one of the most intuitive error messages to understand, the reason it can be hard to find is that you are literally looking for something that does not exist.
# Error Example - R object not found > y Error: object 'y' not found
Now, this example of the error is simple. In real-world programming, this is not where you are likely to get it. It is more likely to result when you have longer object names such as Bureau-of-bureaucratic-bureaucracy-data. In such cases, you may get this error message because you made a typographical error.
What is causing this error?
What triggers the error is the program not being able to find an object name being called. While this is what technically causes this error the real cause boils down to three simple programming mistakes.
- Forgetting to define the object.
- Typographical errors when calling an object.
- Calling the routine before you define the object.
Typographical errors are probably going to be the most common cause of getting this error. This is because when retyping an object’s name there is always the possibility of hitting the wrong key.
How to fix this error.
There are several different ways of fixing this problem. There are three main things that you need to check in dealing with this error.
- Check your spelling and make sure it is the same in both cases. Used copy and paste if needed to get it right.
- Check to make sure that you have actually defined the object.
- See if there is a reason why the routine was called before you defined the object.
In the case where the routine is being called before you define the object, the exists() function will prevent you from getting this error.
# Preventing Error: R object not found > x = c(1, 2, 3) > exists("x")  TRUE > exists("y")  FALSE > if(exists("y")) y else x  1 2 3 > y = c(4, 5, 6, 7) > if(exists("y")) y else x  4 5 6 7
The key to using the exists() function to avoid the object not found error is to use it as the condition in an “if statement” that prevents the calling of the object if it does not yet exist. In most cases, all you will need to do is find and fix a typographical error. However, the exists() function gives you a way to check for it in your code.
Addresses Error: R object not found