Reputation: 59435
I am confused now! First I learned it is not possible in R, but I often forget it and it sometimes works. And then it doesn't work again! I start to recognize the pattern - it works in for loop or in another block statement, but not outside:
for (i in 1:10) {
if (0)
a <- 1
else
a <- 2
b <- 3
}
Doesn't make sense to me... any explanation? And manual reference? In every R resource I read it seemed like brackets are necessary:
if (0) {
a <- 1
} else {
a <- 2
}
PS: not a duplicate, the marked question don't even talk about the variant without brackets, which is core of my question. It is talking about the necessity of the line breaks.
Upvotes: 5
Views: 4383
Reputation:
I would like to contribute to the why part of the question - why there are two different possibilities
hrbrmstr states following in this SO question
When the initial if is followed by a compound expression (indicated by the {} pair) the parser by default is going to expect the expression followed by else to be compound as well. The only defined use of else is with compound expressions. This is even stated in the docs: if(cond) cons.expr else alt.expr where cons.expr and alt.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).
Berry Boessenkool writes:
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.
Upvotes: 0
Reputation: 329
When the entire "if" statement is enclosed in curly brackets (as in the body of a function), you do not need the "else" to be on the same line as the closing bracket of the "if".
This code yields a syntax error:
a <- 1
if (a >1)
{
print("a is greater than 1")
}
else
{
print ("a is not greater than 1")
}
While this does not, solely because of the addition of the first and last brackets:
{
a <- 1
if (a >1)
{
print("a is greater than 1")
}
else
{
print ("a is not greater than 1")
}
}
Upvotes: 8
Reputation: 124997
any explanation?
The short answer here is that you need to either use brackets or put the else
clause on the same line as the if
. From the documentation:
When the if statement is not in a block the else, if present, must appear on the same line as the end of statement2. Otherwise the new line at the end of statement2 completes the if and yields a syntactically complete statement that is evaluated.
So, you can use this:
for (i in 1:10) {
if (0) {
a <- 1
}
else {
a <- 2
}
b <- 3
}
Or this:
for (i in 1:10) {
if (0) a <- 1 else a <- 2
b <- 3
}
Upvotes: 0