问题
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
回答1:
Put the else after if
s bracket
i <- 21
if(i==22){
print(c("xxx"))
}else{
print(c("yyy"))
}
##[1] "yyy"
回答2:
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.
来源:https://stackoverflow.com/questions/23944698/error-unexpected-in-if-print-else-print