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

Categories

0 votes
288 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...