Why does R store the loop variable/index/dummy in memory?

前端 未结 2 1963
粉色の甜心
粉色の甜心 2021-01-11 11:57

I\'ve noticed that R keeps the index from for loops stored in the global environment, e.g.:

for (ii in 1:5){ }

print(ii)
# [1] 5
<         


        
2条回答
  •  一个人的身影
    2021-01-11 12:59

    I agree with the comments above. Even if you have to use for loop (using just side effects, not functions' return values) it would be a good idea to structure your code in several functions and store your data in lists.

    However, there is a way to "hide" index and all temporary variables inside the loop - by calling the for function in a separate environment:

    do.call(`for`, alist(i, 1:3, {
      # ...
      print(i)
      # ... 
    }), envir = new.env())
    

    But ... if you could put your code in a function, the solution is more elegant:

    for_each <- function(x, FUN) {
      for(i in x) {
        FUN(i)
      }
    }
    
    for_each(1:3, print)
    

    Note that with using "for_each"-like construct you don't even see the index variable.

提交回复
热议问题