One common error you may encounter in R is:
Error: unexpected 'else' in "else"
This error usually occurs when you place an else statement at the start of a new line in R.
This tutorial explains how to fix this error in practice.
How to Reproduce the Error
Suppose we attempt to use an if else statement to print a specific string based on the value of a variable:
#define x x #use if else statement to print string if(x print("x is less than 7") } else { print("x is not less than 7") } Error: unexpected 'else' in "else"
We receive an error because we placed the else statement at the beginning of a brand new line.
How to Fix the Error
To fix this error, we simply need to move the else statement up one line so that it appears immediately after the first closing curly bracket:
#define x x #use if else statement to print string if(x print("x is less than 7") } else { print("x is not less than 7") } [1] "x is less than 7"
This time we don’t receive an error and the if else statement prints the string “x is less than 7” since x is indeed less than 7.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix: (list) object cannot be coerced to type ‘double’
How to Fix in R: invalid model formula in ExtractVars
How to Fix in R: replacement has length zero