Recommended way to change variable areas

In C and variants, when you have something like this:

{ tmp1 <- 5 tmp2 <- 2 print(tmp1 + tmp2) } 

7 will be printed, but the variables tmp1 and tmp2 will be removed from the stack after the completion of the area } . I sometimes need similar functionality in R, so I don’t need to clear (many) temporary variables at some point in time.

One way to make this work in R is this:

 (function(){ tmp1 <- 5 tmp2 <- 2 print(tmp1 + tmp2) })() 

Now it seems a little hacky - or it can only be me.

Are there any better or more concise (i.e. more readable) ways to do this in R?

+5
source share
2 answers

You can use local in the R database for this purpose:

 local({ tmp1 <- 5 tmp2 <- 2 print(tmp1 + tmp2) }) 

This way, any variable created within local will disappear as soon as the scope remains.

From ?local :

local evaluates the expression in the local environment.

See ?local more details.


In addition, with (suggested by @Rich Scriven in the comments) can also be used in the R database, where 1 is just dummy data:

 with(1, { tmp1 <- 5 tmp2 <- 2 print(tmp1 + tmp2) }) 

From ?with :

with is a generic function that computes expr in a local environment built from data.

+8
source

Inside the main body of the code, the variables are global. However, since you found that their scope is local within the functions:

 addme <- function(){ tmp1 <- 5; tmp2 <- 2; return (tmp1+tmp2) } 

then addme() call returns the sum, but the variable remains inaccessible outside

 > addme() [1] 7 > tmp1 Error: object 'tmp1' not found 
0
source

Source: https://habr.com/ru/post/1268588/


All Articles