Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...