Why is it that when using an if else statement in R, the "else" cannot be on a new line unless the whole statement is nested within another form of statement, loop or function?
For example, the below code does not work:
x <- 5
if(x<10){
print("x<10")
}
else{
print("x>9")
}
However if we put the whole thing within a loop so that it is indented, suddenly it works fine
for(i in 1:1){
x <- 5
if(x<10){
print("x<10")
}
else{
print("x>9")
}
}
I understand that R wants you to write them like below:
x <- 5
if(x<10){
print("x<10")
}else{
print("x>9")
}
But I don't like how that looks and also want to understand why this syntax / style is only a requirement when the statement is not nested within something else.
Thanks!
This has nothing to do with enforcing a style, but to do with how the R parser works. In essence, when your if
clause is syntactically complete with a newline at the end of its closing bracket, the console thinks you are done with that instruction, and waits for its next instruction. But an else
clause has to be part of the same instruction. If the next instruction starts with an else
, the R parser doesn't know what the else
is referring to.
Let's demonstrate this for clarity. If you paste the following code into the console:
x <- 5
if(x<10){
print("x<10")
}
Then you will see this:
> x <- 5
>
> if(x<10){
+ print("x<10")
+ }
[1] "x<10"
>
Notice that if a line of code is syntactically complete, R will run the code, then print the console marker >
at the start of the next line. If a newline symbol is present in the pasted code, but the code is syntactically incomplete, the console places a +
at the start of each line, indicating that the R parser needs more input before it has syntactically complete code to run.
But if you run your example code, look what happens:
> if(x<10){
+ print("x<10")
+ }
[1] "x<10"
> else{
Error: unexpected 'else' in "else"
> print("x>9")
[1] "x>9"
> }
Error: unexpected '}' in "}"
Your if
statement with its associated brackets was a syntactically complete element, so R ran the code. It printed out [1] "x<10"
as expected, then waited for its next instruction. However, its next instruction was else {
, and the R parser knows that no syntactically correct R code can start with an else. R can't go back in time and undo what it did in the if
clause just because you subsequently write an else
clause.
So, this has nothing to do with enforcing a style. You simply need a way of saying to R "I'm not done yet" after an if
clause. There are various ways to do this. For example, your code would be fine inside a function, or a loop, or brackets. These are just ways of saying to the R parser : "don't run the code yet, I'm not done."
x <- 5
{
if(x<10){
print("x<10")
}
else{
print("x>9")
}
}
#> [1] "x<10"
Created on 2022-02-11 by the reprex package (v2.0.1)