[R] eval and assign in loop problem
Erik Iverson
eriki at ccbr.umn.edu
Fri Jul 9 20:45:18 CEST 2010
>
> for (i in 0:3)
> {
> r = runif(1)
> assign(paste('b',i,sep=''),r)
> }
>
>
> for (i in 1:4)
> {
>
> assign(paste('b',i,sep=''),eval(parse(text=paste('b',i-1,sep=''))))
> }
>
First, b1 is set to b0
Then, b2 is set to b1 (which was just set to b0)
Then, b3 is set to b2 (which was just set to b1, which was just set to b0)
...
All b[i] are set to b0
If this is all you're trying to accomplish, it's much better to keep the
common objects in a vector (or list if they are more complicated) and
use sapply/lapply and vectorized functions to perform the manipulations.
You've managed to use three seldom-needed methods in 2 lines of R code
:) (for loops, assign, and eval(parse(text=)))
More information about the R-help
mailing list