R Errors
Errors
Everyone makes mistakes when they write code, even experienced programmers.
When R cannot run your code, it stops and shows an error message. The message tells you what went wrong, so learning to read it helps you fix the problem fast.
In this example, we try to print a variable that does not exist:
Example
x <- 10
print(y)
Result:
Error in print(y) : object 'y' not foundTry it Yourself »
The message has two parts:
Error in print(y)tells you where the error happened.object 'y' not foundtells you what went wrong: there is no variable calledy.
Common Errors
Here are some errors that beginners often see, and how to fix them.
object not found
You use a variable that does not exist. Often the name is misspelled. Remember that R is case-sensitive, so Name and name are two different variables:
Example
Name <- "John"
print(name)
Result:
Error in print(name) : object 'name' not foundTry it Yourself »
Fix: Use the same name as when you created the variable: print(Name).
could not find function
You call a function that does not exist. Here, print() is written with a capital P:
Example
Print("Hello World!")
Result:
Error in Print("Hello World!") : could not find function "Print"
Try it Yourself »
Fix: Check the spelling of the function: print("Hello World!").
unexpected
R found something in a place where it did not expect it. The message says what R found, for example a symbol or a string. This is often caused by a missing comma, quote or bracket. Here, the comma between the two strings is missing:
Example
paste("Hello" "World")
Result:
Error: unexpected string constant in "paste("Hello" "World""
Try it Yourself »
Fix: Add the missing comma: paste("Hello", "World").
non-numeric argument
You try to do math with a string. "5" has quotes, so it is text, not a number:
Example
num <- "5"
num + 10
Result:
Error in num + 10 : non-numeric argument to binary operatorTry it Yourself »
Fix: Remove the quotes (num <- 5), or convert the text to a number with as.numeric(num).
Warnings
R also has warnings. A warning means that R could run the code, but something looks wrong.
For example, as.numeric() cannot turn the text "hello" into a number. R stores NA (a missing value) in x, and shows a warning:
Example
x <- as.numeric("hello")
Result:
Warning message: NAs introduced by coercionTry it Yourself »
An error stops the program, but a warning does not. Always read warnings: they often point to a bug.
Tip: In the next chapter, you will learn how to handle errors, so that your program can keep running when something goes wrong.