Peng Yu
2009-Nov-22 14:56 UTC
[R] How to make the assignment in a for-loop not affect variables outside the loop?
I know that R is a dynamic programming language. But I'm wondering if there is a way to make the assignment in a for-loop not affect variables outside the loop.> n=10 > for(i in 1:n){+ n=3 + print(n) + } [1] 3 [1] 3 [1] 3 [1] 3 [1] 3 [1] 3 [1] 3 [1] 3 [1] 3 [1] 3> > print(n)[1] 3>
Uwe Ligges
2009-Nov-22 15:17 UTC
[R] 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:> I know that R is a dynamic programming language. But I'm wondering if > there is a way to make the assignment in a for-loop not affect > variables outside the loop. > >> n=10 >> for(i in 1:n){ > + n=3 > + print(n) > + } > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 > [1] 3 >> print(n) > [1] 3 > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.