[R] help with creating new variables using a loop
Uwe Ligges
ligges at statistik.tu-dortmund.de
Sat Feb 9 20:48:16 CET 2013
On 07.02.2013 17:16, christel lacaze wrote:
>
> Hi there,
>
> I've got a set of 10 numeric variables called Mood1 to Mood10 in a dataset called mood. I'm trying to create a set of 10 new variables called m1 to m10 so that m1=Mood1*1, m2=Mood2*2, etc to m10=Mood10*10
>
> Trawling through the internet, I eventually tried the following code:
>
> for (i in 1:10){
> assign(x=paste0("mood$m",i),
> value=paste0("mood$Mood",i)*i,
> envir=.GlobalEnv)
> }
>
Indexing works via
mood[[paste0("Mood", i)]]
However, assignment to separate objects is typically a bad idea, just
aollect them in another data.frame or list.
Uwe Ligges
> unfortunately this doesn't work as it seems the paste0 function returns a list object that only contains the vector's name and not the vector itself.
>
> Hope someone can help...
>
> Christel
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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