if else Error: unexpected '}' in "}" in R

This question already has an answer here:


ANSWERS:


If you're entering code interactively, R thinks the if clause is done as soon as it sees the first close-bracket. Then it "thinks" the else is starting a new statement, which is not allowed. From help("else"):

In particular, you should not have a newline between ‘}’ and ‘else’ to avoid a syntax error in entering a ‘if ... else’ construct at the keyboard or via ‘source’. For that reason, one (somewhat extreme) attitude of defensive programming is to always use braces, e.g., for ‘if’ clauses.

If you use R CMD BATCH then this will work. You could also use brackets, as suggested by the help file:

x <- -5
{ if(x > 0){
     print("Non-negative number")
  } 
  else {
     print("Negative number")
  }
}

or just include the else on the same line as the close-bracket.


It's not your fault. That's the way the R console works! When you type the closing bracket, the console expects there won't be any else if or else clauses, so it executes the if clause.

A workaround is to enclose the whole if.. else clause in brackets, like this:

x <- -5
{   
  if(x > 0){
     print("Non-negative number")
  } 
  else{
     print("Negative number")
  }
}

From this Documentation it states that you need to type it this way.

It is important to note that else must be in the same line as the closing braces of the if statements.

So even if you're not in interactive mode, you may experience issues.



 MORE:


 ? syntax error "SyntaxError: Unexpected keyword 'else'" for JS
 ? syntax error "SyntaxError: Unexpected keyword 'else'" for JS
 ? syntax error "SyntaxError: Unexpected keyword 'else'" for JS
 ? I'm having trouble with the syntax for my compare function for javascript
 ? Syntax for if/else statement in Haml - unexpected keyword else?
 ? Syntax error: Unexpected token else: specific code
 ? Codecademy "SyntaxError: Unexpected token else"
 ? SyntaxError: Unexpected token {
 ? JavaScript Syntax Error
 ? JavaScript Syntax Error