logo

Using else if Statements in R: Solving the Error: unexpected else in else Issue 📂R

Using else if Statements in R: Solving the Error: unexpected else in else Issue

Overview

R does not have a branching statement like a switch statement, so you need to divide branches by connecting multiple if statements. Here, this conditional statement can be the same for if and else in every programming language, but it’s peculiar that only else if can be different. They might be written together as elseif or even abbreviated like elif, and R uses properly spaced else if. Even as you become able to handle various programming languages and your programming skills improve, these minor differences always tend to be confusing.

for(i in 1:3)
{
  if(i==1) {print('하나')}
  else if(i==2) {print('둘')}
  else {print('셋')}
}

The result of the branching statement is as follows.

20171111_144344.png

Problem

It goes without saying, but by increasing else if, you can create more branches. On the other hand, there are cases where else causes an error in the conditional statement even though it seems to be correct. There are many such problems when you just want to do a simple check in the console.

Error: unexpected 'else\' in "else"

Cause

20171111_144353.png

Such errors occur because if does not necessarily require else to be satisfied. if is all about judging whether the condition is satisfied by itself and then executing the given code if it is true. Thus, the if line has done all its functions, and the next line starting new is led by else.

Solution

The problem can be easily solved by just putting the two lines inside a block { }.

20171111_144557.png

Because they are within a block, it is assumed that the if statement would be below else, and the code runs correctly.