How to fix Error: unexpected ‘else’ in R

To fix this error, you need to find the syntax error in the code that is causing the unexpected ‘else’ statement. Check for missing braces or parentheses and make sure that all ‘if’ statements have a corresponding ‘else’ statement. Once the syntax is corrected, the error should disappear.


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 <- 5

#use if else statement to print string
if(x < 7) {
  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 <- 5

#use if else statement to print string
if(x < 7) {
  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.

The following tutorials explain how to fix other common errors in R:

x