For example, inside a for loop, I want to define some variables to do some operation, but I want them to be automatically removed once the iteration is over.
However, if I assing a value to a variable using <-
, even after the execution of the loop ends, the variable still persists and I have to remove it, manually, which is quite annoying.
This answers illustrates the use of local
within a loop in R:
number <- 1:5
res <- numeric(5)
local(for(i in number){
res2 <-res[i] + 42
print(res2)
})
[1] 42
[1] 42
[1] 42
[1] 42
[1] 42
The above does not create res2
in .GlobalEnv
unlike the following:
for(i in number){
res2 <-res[i] + 42
print(res2)
}
Alternatively, you could avoid loops and use *apply
and/or use functions that use local variables by design. See examples here