Decoding error messages in R can be difficult for newcomers, that’s why I’m working on helpPlease. However, in the meantime, it’s important to be able to understand R errors and warnings in more detail than simply ‘R says no’. So here’s a quick rundown:
R gives both errors and warnings
An error is “R says no”. It’s R’s way of telling you why the chunk of code is not possible to execute.
Warnings mean “R says OK sure but maybe you won’t like what you’re going to get”. It’s R’s way of telling you the code is behaving in a different way than you might reasonably expect.
Decoding an error message
The error message typically comes in three parts. Here’s a common example from my code: I’ve tried to access a part of a array that doesn’t exist – my array has a column dimension of 5, so when R goes looking for a the 100th column it’s understandably confused and just gives up.
There are three main parts to this message:
- The declaration that it is an Error
- The location of the error – it’s in the line of my code fit[5,100,]
- The problem this mistake in my code caused: the subscript is out of bounds, i.e. I asked R to go an retrieve a part of this array that did not exist.
Decoding a warning message
Warning messages can be very variable in format, but there are often common elements. Here’s a common one that ggplot gives me:
Here I’ve asked ggplot2 to put a line chart together for me, but some of my data frame is missing. Ggplot2 can still put the chart together, but it’s letting me know I have missing values.
While warning messages can be very variable, there are some common elements that turn up fairly regularly:
- The declaration of a warning
- The behaviour being warned about
- The piece of code that caused the warning
Now that you know what warnings and errors are and what’s in them: how do you find out what they mean?
Where can you find help?
There’s lots of information out there to help you decode your warning and error messages. Here are some that I use all the time:
- Typing ? or ?? and the name of the function that’s going wrong in the console will give you help within R itself
- Googling the error message, warning or package is often very useful
- Stack Overflow or the RStudio community forums can be searched for other people’s (solved!) problems
- The vignettes and examples for the package you’re using are a wealth of information
- Blog posts that use the package or function you are can be a very good step-by-step guide of how to prepare your data for the tool you’re trying to use
- Building a reprex (a reproducible example) is a good way of getting ready to ask a question on Stack Overflow or the R community forums.
Good luck! And in the meantime, if you should come across an R message that could use explaining in plain text I’d really love to hear from you (especially if you’re new!).