Dear John,

Thank you very much for the explanation. It cleared up my confusion about the syntax of "if ... else...", which in the help page of "if" said:
```
In particular, you should not have a newline between ‘}’ and
     ‘else’ to avoid a syntax error in entering a ‘if ... else’
     construct at the keyboard or via ‘source’.
```

Best,
Jinsong


On 2022/10/21 21:49, John Fox wrote:
Dear Jinsong,

When you enter these code lines at the R command prompt, the interpreter evaluates an expression when it's syntactically complete, which occurs before it sees the else clause. The interpreter can't read your mind and know that an else clause will be entered on the next line. When the code lines are in a function, the function body is enclosed in braces and so the interpreter sees the else clause.

As I believe was already pointed out, you can similarly use braces at the command prompt to signal incompleteness of an expression, as in

> {if (FALSE) print(1)
+ else print(2)}
[1] 2

I hope this helps,
 John


______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to