[R] unexpected 'else' in " else"

John Fox j|ox @end|ng |rom mcm@@ter@c@
Fri Oct 21 15:49:30 CEST 2022


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

-- 
John Fox, Professor Emeritus
McMaster University
Hamilton, Ontario, Canada
web: https://socialsciences.mcmaster.ca/jfox/
On 2022-10-21 8:06 a.m., Jinsong Zhao wrote:
> Thanks a lot!
> 
> I know the first and third way to correct the error. The second way 
> seems make me know why the code is correct in the function 
> stats::weighted.residuals.
> 
> On 2022/10/21 17:36, Andrew Simmons wrote:
>> The error comes from the expression not being wrapped with braces. You 
>> could change it to
>>
>> if (is.matrix(r)) {
>>     r[w != 0, , drop = FALSE]
>> } else r[w != 0]
>>
>> or
>>
>> {
>>     if (is.matrix(r))
>>         r[w != 0, , drop = FALSE]
>>     else r[w != 0]
>> }
>>
>> or
>>
>> if (is.matrix(r)) r[w != 0, , drop = FALSE] else r[w != 0]
>>
>>
>> On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao, <jszhao using yeah.net> wrote:
>>
>>     Hi there,
>>
>>     The following code would cause R error:
>>
>>      > w <- 1:5
>>      > r <- 1:5
>>      >         if (is.matrix(r))
>>     +             r[w != 0, , drop = FALSE]
>>      >         else r[w != 0]
>>     Error: unexpected 'else' in "        else"
>>
>>     However, the code:
>>              if (is.matrix(r))
>>                  r[w != 0, , drop = FALSE]
>>              else r[w != 0]
>>     is extracted from stats::weighted.residuals.
>>
>>     My question is why the code in the function does not cause error?
>>
>>     Best,
>>     Jinsong
>>
>>     ______________________________________________
>>     R-help using 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
>>     <http://www.R-project.org/posting-guide.html>
>>     and provide commented, minimal, self-contained, reproducible code.
>>
> 
> ______________________________________________
> R-help using 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.



More information about the R-help mailing list