R Error: Unexpected else in “else” (2 Examples)

 

In this R tutorial you’ll learn how to solve the error unexpected else in “else”.

The table of content looks as follows:

Let’s just jump right in.

 

Example 1: Reproduce the Error – unexpected else in “else”

The following code illustrates how to replicate the error message unexpected else in “else” in R. Let’s assume we want to create an if else statement:

if(TRUE) {        # Reproducing the error
  "x"
}
else {
  "y"
}
# Error: unexpected 'else' in "else"

Gosh! We received an error message!

The reason for this error is that we didn’t write the else statement to the same line as the closing curly bracket of the if statement.

I’ll show you how to fix this issue in the following example…

 

Example 2: Fix the Error – unexpected else in “else”

Example 2 explains how to deal with the error message unexpected else in “else”. Let’s again run our if else statement, but this time we are executing the else statement one line higher:

if(TRUE) {        # Fixing the error
  "x"
} else {
  "y"
}
# [1] "x"

Works fine!

 

Video, Further Resources & Summary

Do you need further info on the R codes of this tutorial? Then you might want to have a look at the following video of my YouTube channel. In the video, I illustrate the R programming codes of this article.

 

The YouTube video will be added soon.

 

Furthermore, you might want to read the other articles on my homepage.

 

This article showed how to get rid of the error message unexpected else in “else” in the R programming language. Let me know in the comments below, in case you have further questions.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top