[R] assign

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Wed Jan 7 18:35:46 CET 2004


Perez Martin, Agustin wrote:

>DeaR useRs:
>
>I would like to assign a values in an object using a loop 'for'.
>This is a reduce example of my problem, my real problem is a few
>complicated:
>
>for (j in 1:10) {
>	x.j<-rnorm(100)
>}
>
>I want to create 10 objects as "x.1, x.2, ... , x.9, x.10" with values in
>it.
>I used the "assign" function but nothing happens.
>Thank you very much
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>  
>
Use eval or assign:

 > for(j in 1:10) eval(parse(text=paste("x",j,"<-",j,sep="")))
 > x1
[1] 1
 > x8
[1] 8
 > for(j in 1:10) eval(parse(text=paste("x",j,"<-rnorm(10)",sep="")))
 > x1
 [1]  0.49045324  0.44842510 -1.18015351 -0.04325187 -0.75345939 -0.99181309
 [7]  0.62517301 -0.68466635  0.33383560 -0.62189500
 > x2
 [1] -0.4344948  2.0276137  1.2783173  1.1170551  0.3546490 -0.0748969
 [7] -0.8817247 -1.4649175 -1.5461995 -0.6575016
 > for(j in 1:10) assign(paste("y",j,sep=""),rnorm(10))
 > y1
 [1] 1.7255925 0.4993323 1.8846513 0.2058971 0.2284036  -3.1971553
 [7]  -0.2629365 0.2724788  -0.9911388  -0.6341857
 > y2
 [1] 0.11301503  -1.28497666 0.40670853 0.08479014 1.05818411  -1.10843908
 [7] 1.30441911  -0.49050833  -1.21438645 0.03923849
ls()
 [1] "j"   "x1"  "x10" "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "y1"
[13] "y10" "y2"  "y3"  "y4"  "y5"  "y6"  "y7"  "y8"  "y9"

pw




More information about the R-help mailing list