[R] return value of {....}

Valentin Petzel v@|ent|n @end|ng |rom petze|@@t
Mon Jan 9 16:48:09 CET 2023


Hello Akshai,

I think you are confusing {...} with local({...}). This one will evaluate the expression in a separate environment, returning the last expression.

{...} simply evaluates multiple expressions as one and returns the result of the last line, but it still evaluates each expression.

Assignment returns the assigned value, so we can chain assignments like this

a <- 1 + (b <- 2)

conveniently.

So when is {...} useful? Well, anyplace where you want to execute complex stuff in a function argument. E.g. you might do:

data %>% group_by(x) %>% summarise(y = {if(x[1] > 10) sum(y) else mean(y)})

Regards,
Valentin Petzel

09.01.2023 15:47:53 akshay kulkarni <akshay_e4 using hotmail.com>:

> Dear members,
>                              I have the following code:
> 
>> TB <- {x <- 3;y <- 5}
>> TB
> [1] 5
> 
> It is consistent with the documentation: For {, the result of the last expression evaluated. This has the visibility of the last evaluation.
> 
> But both x AND y are created, but the "return value" is y. How can this be advantageous for solving practical problems? Specifically, consider the following code:
> 
> F <- function(X) {  expr; expr2; { expr5; expr7}; expr8;expr10}
> 
> Both expr5 and expr7 are created, and are accessible by the code outside of the nested braces right? But the "return value" of the nested braces is expr7. So doesn't this mean that only expr7 should be accessible? Please help me entangle this (of course the return value of F is expr10, and all the other objects created by the preceding expressions are deleted. But expr5 is not, after the control passes outside of the nested braces!)
> 
> Thanking you,
> Yours sincerely,
> AKSHAY M KULKARNI
> 
>     [[alternative HTML version deleted]]
> 
> ______________________________________________
> 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