Error: unexpected '}' in “}” if…print()…else…print() [duplicate]

天大地大妈咪最大 提交于 2019-12-24 12:43:30

问题


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 ifs 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!