[R] unexpected 'else' in " else"

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Wed Oct 26 12:03:30 CEST 2022


This is explained in books about S and R.
The first place to look is of course
> ?"if"
which says
<quote>
     Note that it is a common mistake to forget to put braces ('{ ..
     }') around your statements, e.g., after 'if(..)' or 'for(....)'.
     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'.  For that reason, one
     (somewhat extreme) attitude of defensive programming is to always
     use braces, e.g., for 'if' clauses.
</quote>

The basic issue is that the top level wants to get started
on your command AS SOON AS IT HAS A COMPLETE COMMAND,
and if (...) stmt
is complete.  It's not going to hang around "Waiting for Godot"
for an 'else' that might never ever ever turn up.  So
   if (x < y) z <-
   x else z <- y
is absolutely fine, no braces needed, while
   if (x < y) z <- x
   else z <- y
will see the eager top level rush off to do your bidding
at the end of the first line and then be completely
baffled by an 'else' where it does not expect one.

It's the same reason that you break AFTER infix operators
instead of BEFORE.
   x <- y +
   z
works fine, while
   x <- y
   + z
doesn't.



On Fri, 21 Oct 2022 at 22: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
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list