1

I WAS GIVEN ANSWER: THE if's closing BRACKET should be BEFORE ELSE not ABOVE.

This error had already been discussed here: Error: unexpected '}' in " }" and https://stackoverflow.com/questions/15303559/error-unexpected-in But they do not help me.

I run the code:

i <- 21
if(i==22){
 print(c("xxx"))
}
else{
 print(c("yyy"))
}

And get an error

else{ Error: unexpected 'else' in "else"
print(c("yyy")) [1] "yyy" } Error: unexpected '}' in "}"

I use Rstudio on Windows, quite new R version and Rstudio, but not sure where to check it

Community
  • 1
  • 1
user3442434
  • 13
  • 1
  • 4

2 Answers2

6

Put the else after ifs bracket

i <- 21
if(i==22){
  print(c("xxx"))
}else{
  print(c("yyy"))
}

##[1] "yyy"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • From the ?"if" help page: 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 – MrFlick May 29 '14 at 23:38
0

This code will work in a function or when enclosed in braces, but not elsewhere because else is on a new line. See the duplicate question for more details.

Good practice is to put the else on the same line as the }. Then it will work for both.

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142