Andrew Simmons is correct but doesn't explain why the code works in the 
package. This is one of only two differences I have found between running code 
at the command line and running it from a file. (The other difference is that 
code in a file is often executed in an environment other than .GlobalEnv. There 
is some related sugar around packages that usually makes things work the way a 
user would want.) At the command line, R executes code whenever RETURN could be 
interpreted as the end of a statement. "If(�.) �. RETURN" is ambiguous: will it 
be followed by "else", or is it a complete statement? If it's in a file or 
wrapped in a block or other structure that obviously hasn't ended yet then R 
will wait to see the next line of input, but if it could be a complete 
statement then not executing it would cause a lot of frustration for users. 
Once the statement is executed, R expects another statement, and no statement 
begins with "else". (Maybe the interpreter could be enhanced to keep the "if" 
open under some conditions, but I haven't thought it through. In particular, 
"if" without "else" is NULL if the condition is FALSE, so it might be necessary 
to undo an assignment, and that seems very difficult.)

Regards,
Jorgen Harmse.


On Fri., Oct. 21, 2022, 05:29 Jinsong Zhao, <jsz...@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@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]]




------------------------------

Subject: Digest Footer

_______________________________________________
R-help@r-project.org mailing list
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.


------------------------------

End of R-help Digest, Vol 236, Issue 19
***************************************

        [[alternative HTML version deleted]]

______________________________________________
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