2

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.

Our
  • 986
  • 12
  • 22
  • Anything inside a function is local so best to use functions instead of loops or maybe use `local`? – NelsonGon May 13 '20 at 15:08
  • @NelsonGon as far as I know, R does not have any syntax like `local`, like python has (I have just tried using that prefix while defining a variable in a for loop, it didn't wokr) – Our May 13 '20 at 15:11
  • I rarely write explicit loops in R, could you add some example? See [these](https://stackoverflow.com/questions/29639093/why-does-r-store-the-loop-variable-index-dummy-in-memory) alternatives. – NelsonGon May 13 '20 at 15:12
  • 1
    This uses `local` but then everything is `local`: `number <- 1:5; res <- numeric(5); local(for(i in number){ print(res[i] + 2) })` – NelsonGon May 13 '20 at 15:19
  • 1
    @NelsonGon oh, I didn't know that one could from a for loop like in the accepted answer. – Our May 13 '20 at 15:19
  • @NelsonGon You gave me 3 different ways of doing exactly what I was asking; thanks a lot. I suggest you turn your comment into an answer. – Our May 13 '20 at 15:24

1 Answers1

3

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

shafee
  • 15,566
  • 3
  • 19
  • 47
NelsonGon
  • 13,015
  • 7
  • 27
  • 57