[R] help with creating new variables using a loop

arun smartpink111 at yahoo.com
Sat Feb 9 20:59:52 CET 2013

 mood<- data.frame(Mood1=1:5,Mood2=6:10,Mood3=11:15)
lapply(seq_along(mood),function(i) i*mood[i])

----- Original Message -----
From: christel lacaze <christellacaze at hotmail.co.uk>
To: r-help at r-project.org
Sent: Thursday, February 7, 2013 11:16 AM
Subject: [R] help with creating new variables using a loop

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){

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...

    [[alternative HTML version deleted]]

R-help at r-project.org mailing list
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