Skip to content
Prev 201162 / 398503 Next

How to make the assignment in a for-loop not affect variables outside the loop?

Either use local as in:

n=10

local(for(i in 1:n){
      n=3
      print(n)
})

print(n)


or write a function that is evaluated in its own environment:

n=10

MyLoopFoo <- function(){
     for(i in 1:n){
         n <- 3
         print(n)
     }
}

MyLoopFoo()

print(n)




Uwe Ligges
Peng Yu wrote: