[R] unexpected 'else' in " else"

Jinsong Zhao j@zh@o @end|ng |rom ye@h@net
Fri Oct 21 16:27:35 CEST 2022

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’.


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

More information about the R-help mailing list