Reputation: 11
I'm quit new to R programming. While I was trying to write my first if else statement I came across a weird behaviour which I don't understand.
When I run below code:
x = 4;
y=4;
if (x==y) {
print('they are equal');
} else {
print('they are not equal');
}
I get no error and I get the expected output. However when I change the indentation of the same exact code as below:
if(x==y){print('they are equal');}
else{print('they are not equal');}
I get an error message saying that 'Error: unexpected 'else' in "else"'.
So does this means that R is an indentation sensitive language like Python?
Upvotes: 1
Views: 577
Reputation: 499
To my limited experience, in R syntex, else
statement should start from the same line where if
statement ends. Otherwise, it won't work. And R is NOT indenting sensitive. For example,
This will work
if(x==y){print('they are equal')
} else
{print('they are not equal')}
[1] "they are equal"
Even this will work
if(x==y){print('they are equal')} else
{print('they are not equal')}
[1] "they are equal"
This will also work
if(x==y){print('they are equal')} else {print('they are not equal')}
[1] "they are equal"
But the code you have written doesn't work because else
statement doesn't start from the same line where if
statement ends. Another example would be,
This won't work
if(x==y){print('they are equal')}
else {
print('they are not equal')}
Also, you don't need the semi-colons.
Upvotes: 2