[R] help with creating new variables using a loop

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Feb 7 18:47:02 CET 2013

On Thu, Feb 7, 2013 at 4:16 PM, christel lacaze
<christellacaze at hotmail.co.uk> wrote:
> Hi there,
> I've got a set of 10 numeric variables called Mood1 to Mood10 in a dataset called mood.

 That's where you went wrong in the first place. Don't use variable
names for indexing purposes.

 You should have created one variable, a list, where each element is
one of your Mood1, Mood2 etc variables. You can do that:

Mood = list(Mood1,Mood2,Mood3 [etc])

 but its easier to create the right thing in the first place.

 Then looping is simple, and intuitive. Just get Mood2[[i]] where i is
your loop variable. No mucking with paste and get and all that stuff
we should have left behind years ago...

>  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

 What you mean is you want to create a new variable, a list, with 10 elements.

 m = list()
 for(i in 1:10){m[[i]]=i*Mood[[i]]}

or even:

 m = lapply(1:10,function(i){i*Mood[[i]]})

this kind of thing is so much easier once you've put everything in an
indexable list, I'm not going to tell you how to paste names together.
It can be done, but... yuck.


More information about the R-help mailing list