Code errors can be frustrating, but theyâre actually trying to help by telling you what went wrong. Understanding how to read error messages, debug your code, and ask for help effectively will save you time in fixing these errors.
Understanding errors, warnings, and messages
R uses three types of âconditionsâ with different severity for issues with your code: errors, warnings, and messages. Regardless of severity, they should be read carefully as they provide useful information for improving your code.
Errors đ¨
Errors stop your code from running, meaning that you wonât get any results. Errors indicate a problem with your code that must be fixed before execution can continue.
Try to cause the sum()
function to raise an error:
Ensure that all elements you are attempting to sum are numeric. Mixing data types like characters and numbers will result in an error.
sum(c(1, 3, "apple"))
There are many error messages that you might encounter, hereâs a few common ones with some tips on how to fix them:
Error: object 'x' not found
The variable
x
does not exist in your environment. Have you typed the variable name correctly? Perhaps it actually doesnât exist, and you need to create it by running your earlier code?Error: cannot open the connection
The file path youâre trying to read does not exist or is incorrect. Carefully compare your file path with the location of the file on your computer.
Error: could not find function "mutate"
The function is from a package that has not been loaded with
library()
.Error in sample$x : object of type âclosureâ is not subsettable
sample
is a function (aka a âclosureâ), and not a dataset with anx
variable.Check the names of your variables, and try to use dataset names that donât match function names (avoid
data
,sample
,df
, anddt
).Error in log(x, na.rm = TRUE) : unused argument (na.rm = TRUE)
You provided an argument that the function does not use. Check the help file for the function, and see which argument names are usable.
Error in log(...) : argument "x" is missing, with no default
A required argument was not provided, for example
log()
without any numbers to log. Check the help file to understand how to provide the missing argument.Error in library(package) : there is no package called 'package'
The package is not installed, install it with
install.packages("package")
.
Errors stopping your code can be frustrating, but theyâve just saved you from something much worse: incorrect results. Situations where the code runs without complaints but produces incorrect results are known as silent errors.
Silent errors are arguably the worst type of coding problem fix. They donât give a helpful message about what went wrong and you might not even notice the problem until much later. Carefully check the results of your code to identify any unreasonable output that might be from a silent error.
Warnings â ď¸
Warnings donât stop execution but indicate something might be wrong. Your code runs, but the result may not be what you expect. After reading the warning, you should take a close look at your code and the output and make changes if the result isnât right.
Trigger a warning by using log() with negative values.
The log()
function accepts numbers greater than zero. If a negative number is used, it will produce a warning due to an invalid argument within its domain.
<- log(-1) # This will produce a warning since log of negative numbers is undefined result
Other common warnings include:
Warning: NAs introduced by coercion
R tried to convert data to a different type (e.g.,
as.numeric("text")
) and failed, replacing invalid values withNA
.Warning: number of items to replace is not a multiple of replacement length
You tried to assign values to a vector of a different length (e.g.,
x[1:5] <- 1:3
). This ârecyclesâ values to get the replacement length (5), sox[1:5]
will now containc(1, 2, 3, 1, 2)
rather than just1:3
.Warning: Removed X rows containing missing values (geom_point)
ggplot2 removed rows with
NA
s before plotting a the points, so be careful since any patterns in the missing values will not be evident in the plot.Warning: package âdplyr' was built under R version X.Y.Z
The installed package was built for a different version of R than what you are currently using. This is usually ok, but it is safest to reinstall the problematic packages.
Messages đŹ
Messages are used to communicate important details about the codeâs execution. They donât necessarily indicate a problem with your code or results, but they should be read carefully to understand something important about your code or result.
For example, a message informs you of newly masked objects when you load a package like dplyr
. Masked objects are usually functions (e.g. lag()
) which are replaced by functions of the same name from the package. You can explicitly use a function from a specific package with stats::lag()
or dplyr::lag()
to remove any ambiguity.
Loading the dplyr
package will produce a message regarding masking when function names overlap with those in base R.
library(dplyr)
Troubleshooting problems
Read the message đ
The first step is to carefully read the error message, it often contains clues into where and why the code didnât run. With some time and experience, youâll begin to identify these errors and fix your code quickly based on the message alone!
Some of the most common (and most confusing) error messages were described earlier, but if youâre having trouble understanding the message then you might need to search for more information.
Search the message đ
Error messages can be confusing, and even after carefully reading the message it may be difficult to ascertain what the problem is.
Chances are youâre not the first person to encounter this problem and thereâs a well explained solution waiting for you on the internet - you just need to find it. Just copy the error exactly, add some relevant contextual keywords like âRâ and search!
With some luck, youâll be met with a series of StackOverflow threads, blog posts and other websites explaining the solution to the exact problem youâre facing.
Add double quotes around the error message. This searches for those exact words in that exact order.
Only search generic parts of the error message (donât include specifics of your code or variable names)
Add keywords relating to the problem, like the language âRâ, the package âdplyrâ, and the context âjoining dataâ.
If youâre looking for solutions on a specific website, add
site:<domain>
to the search. For example,site:stackoverflow.com
.
Divide and conquer đŞ
If you understand the message, but have no idea where the problem stems from - try running smaller sections of your code to see if that small section causes the error. Once you identify the small section of code causing the error, it should be slightly easier to find the issue in your code.
Read the documentation đ
Râs built-in documentation can help you understand how functions are supposed to be used.
Use ?function_name
or help(function_name)
to access a functionâs help page, which includes descriptions, usage examples, and default values. You might also find reading the package vignettes with vignette(package="dplyr")
useful, they offer guided introductions into how to use the package.
Turn it off and on again đ
The age old classic (but sometimes it really does work!).
In R, you donât necessarily need to restart your whole computer, but instead you can try restarting RStudio, or your R session. Usually I would restart R, which can be done in RStudio in two ways:
- âSessionâ on the top menu bar, then âRestart Râ
- Ctrl-Shift-F10Ctrl-Shift-F10 (Windows) or Cmd-Shift-F10Cmd-Shift-F10 (Mac)
This can fix your problem by resetting your environment to a clean state. Re-running your code without extra unused packages loaded or old variables in the environment might just work!
Asking for help
Once youâve carefully read the error, searched the web, and tried everything else you can think of, itâs time to ask others for help.
Asking good questions
To get useful help, it is important that you ask a good question. Consider answering these two equivalent questions, which is easier to understand?
Writing a good question will help you and others understand your problem, and you might even find the solution in the process of writing it! Hereâs some tips for writing good questions:
Be clear and concise
Explain what youâre trying to do and what isnât working.
Explain what you expected
Describe the output or behaviour you were hoping for.
Provide a minimal reproducible example (reprex)
Share a small, self-contained snippet of code that reproduces the issue. The
{reprex}
package will help you do this.Style your code
Use a code style with proper indentation and spacing to make it easy to read.
Include the full error message
Copy and paste the exact error instead of summarising it.
Show what youâve already tried
Briefly mention other solutions youâve tried to avoid duplicate suggestions.
Creating minimal reproducible examples
A minimal reproducible example (MRE) is essential for effectively communicating problems with code. The process of creating a MRE might also help you resolve the problem yourself!
The guiding principles of creating a minimal reproducible example are:
Minimal
Minimising code and data makes it easier for others to find the problem and offer a solution. Isolating the problem down to just a few lines of code or rows of data can help you (and those helping you) understand exactly where the problem is caused.
Remove unnecessary code
Include as little code as possible to show the problem.
Use small datasets
Prefer built-in datasets or create/sample small example datasets.
Avoid external dependencies
Remove any unused packages or files that are irrelevant to the problem.
In the bad/good code example, the good code is more minimal because it removes the irrelevant ggplot2 code.
Reproducible
Reproducible code includes all elements needed recreate the problem on a different computer, including:
Required packages
If external packages are needed, include loading the packages in your MRE.
Used datasets
If you canât use built-in datasets, then ideally the minimal dataset is created with code without separate data files. You can create a dataset directly with
data.frame()
, or convert any existing R object into code withdput()
. Try usingdput()
with theletters
vector.Set random seeds
If your problem includes randomisation (e.g.
sample()
, or random samples from distributions), you should also includeset.seed()
at the top of your MRE with a seed that reproduces the problem.
The good code example above is more reproducible because it directly embeds the dataset into the code. In the process of making the MRE (specifically thinking about the required packages for the code) might result in the discovery that this problem is resulting from not loading dplyr with library(dplyr)
!
Sometimes the error is specific to your system, and isnât easily reproduced on other computers. Some issues can be specific to other things about your system such as your operating system, system language/locale, R version, or R package versions.
To include useful information about your system, include sessioninfo::session_info()
at the end of your example. If youâre using {reprex}
to create your MRE you can use repex(session_info = TRUE)
.
Example
The minimal and reproducible code you write should be an example of the problem you are facing!
Clearly state the issue
Explain what you expect versus what happens.
Ensure clarity
Add code comments to highlight your intention and the problem.
The good code example clearly describes the goal and unexpected result.
{reprex}
package
The {reprex}
package helps you share reproducible examples by running the example code in a clean environment and then copying a neatly formatted version of your code and its results (including tables, figures, and more).
To create a reprex, simply:
- Copy the example code that youâve made minimal and reproducible,
- Run
reprex::reprex()
, or click `Render reprex...
in the Addins menu and follow the prompts, - When the results are ready, youâll find a preview of the MRE pop-up in the Viewer tab of RStudio (and the markdown code for sharing it copied to your clipboard),
- Paste the results into the help forum of your choice (some useful places are listed below).
View this short clip for a guided walkthrough of using the reprex
package by itâs creator!
Where to ask for help
Class Discussion Forum (e.g. Moodle) | If youâre preparing for your Monash University course, a good place to ask for help is the discussion forum on Moodle. You can also seek assistance from your lecturers and tutors. |
Ask an LLM | There are many large language models (LLMs) that can help you write and debug code. However, AI tools should be used with caution. While it can assist in troubleshooting errors, it may not always provide the best solution. You should still try to understand what the code is doing and why itâs causing an error to avoid using code from AI which may be producing inaccurate results (despite running without error). |
Consultations | Ask your lecturers and tutors for help during consultation sessions, which are available for any content-related difficulties, including debugging code.
|
Stack Overflow | This is a platform where you can search for solutions and ask for help. It is likely that people have already asked similar questions related to your error and you can try the solutions provided by others under the question. Thoroughly search for similar questions already asked on the website before asking for help with your problem. |
Posit Community | This is a community channel for RStudio users. Similar to Stack Overflow, you can ask questions and also find solutions. |
GitHub | If youâve thoroughly investigated your error and believe the issue lies in the package rather than your code, you can contact the packageâs developer. Most R packages are maintained on GitHub, and developers typically prefer problems with their packages reported in the GitHub repositoryâs issuesâjust make sure that a similar issue hasnât already been reported! |
Answering questions on the forum can help consolidate your understanding and prepare you for asking and answering questions in other forums such as Stack Overflow.