Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

r - if - else if - else statement and brackets

I understand the usual way to write an "if - else if" statement is as follow:

if (2==1) {
  print("1")
} else if (2==2) {
  print("2")
} else {
  print("3")
}

or

if (2==1) {print("1") 
} else if (2==2) {print("2")
} else print("3")

On the contrary, If I write in this way

if (2==1) {
  print("1")
} 
else if (2==2) {
  print("2")
}
else (print("3"))

or this way:

if (2==1) print("1") 
else if (2==2) print("2")
else print("3")

the statement does NOT work. Can you explain me why } must precede else or else if in the same line? Are there any other way of writing the if-else if-else statement in R, especially without brackets?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. Remember, you can use if without adding else.

Your third example will work in a function, because the whole function is defined before being executed, so R knows it wasn't done yet (after if() do).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...