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?
if
is followed by a compound expression (indicated by the{}
pair) the parser by default is going to expect the expression followed byelse
to be compound as well. The only defined use ofelse
is with compound expressions. This is even stated in the docs:if(cond) cons.expr else alt.expr
wherecons.expr
andalt.expr
are defined to be compound. As @Berry indicated, you can use the way R parses function definitions to work around this, but it'd be better to be consistent in bracket use (IMO). - hrbrmstr{ bad if-else expr }
or in a function which is more commonfunction() { bad if-else expr}
, it will work - rawr