Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way for variable scoping [duplicate]

Tags:

scope

r

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

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

a 7 will be printed, but the tmp1 and tmp2 variables will be removed from stack once the scope } ends. I sometimes want similar functionality in R so that I do not have to clean up (many) temporary variables after some point in time.

One way to make this work in R is like this:

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

Now that seems a bit hackish -- or it may be just me.

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

like image 936
Davor Josipovic Avatar asked Jun 06 '17 11:06

Davor Josipovic


1 Answers

You might want to use local in base R for that purpose:

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

So any variable created within the scope of local will vanish as soon as the scope is left.

From ?local:

local evaluates an expression in a local environment.

See ?local for more details.


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

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

From ?with:

with is a generic function that evaluates expr in a local environment constructed from data.

like image 195
989 Avatar answered Nov 14 '22 21:11

989