[R] Odp: Creating and assigning variable names in loop
Petr PIKAL
petr.pikal at precheza.cz
Thu Dec 22 08:06:26 CET 2011
Hi
You probably want this cycle for some reason but if you know how many
labels you want you just can
label <- paste("score", 1:3, sep="_")
> label
[1] "score_1" "score_2" "score_3"
Then instead of assigning names in a cycle
you can
label<-c(names(samp_data), label)
for( i in 1:3) {
samp_data <- cbind(samp_data, x1+(x2*i))
}
names(samp_data) <-label
Regards
Petr
> Hello List
>
> I am trying to create and assign variable names in loop, but not able to
get
> expected variable names.
>
> Here is the sample code
>
> n = 10
> set.seed(1)
> x1 = rnorm(n,0)
> x2 = rnorm(n,0)
> samp_data <- data.frame(x1,x2)
>
> for( i in 1:3) {
> label <- paste("score", i, sep="_")
> assign(label, value =x1+(x2*i) )
> samp_data <- cbind(samp_data, get(label))
> }
>
> > head(samp_data)
> x1 x2 get(label) get(label)
> get(label)
> 1 -0.6264538 1.51178117 0.8853274 2.3971085 3.9088897
> 2 0.1836433 0.38984324 0.5734866 0.9633298 1.3531730
> 3 -0.8356286 -0.62124058 -1.4568692 -2.0781098 -2.6993504
> 4 1.5952808 -2.21469989 -0.6194191 -2.8341190 -5.0488189
> 5 0.3295078 1.12493092 1.4544387 2.5793696 3.7043005
> 6 -0.8204684 -0.04493361 -0.8654020 -0.9103356 -0.9552692
>
> I am expecting new variables to be created in the samp_data are
> score_1 score_2 score_3, instead get(label) get(label) get(label)
> Where am I going wrong?
>
> Thanks in advance
> ~Ajit
>
> --
> View this message in context:
http://r.789695.n4.nabble.com/Creating-and-
> assigning-variable-names-in-loop-tp4221080p4221080.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
More information about the R-help
mailing list