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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With