Hello,
I have a dataframe (Lx) with 5 Lb, and 5 Lw variables. I want to
create several variables according to the loop presented below (data
attached).
Lx <- read.csv("Lx.csv", header=T, sep=",")
for (i in 1:20) {
Lx$sb1[i] <- Lx$Lb1[i+1]/Lx$Lb1[i]
Lx$sb2[i] <- Lx$Lb2[i+1]/Lx$Lb2[i]
Lx$sb3[i] <- Lx$Lb3[i+1]/Lx$Lb3[i]
Lx$sb4[i] <- Lx$Lb4[i+1]/Lx$Lb4[i]
Lx$sb5[i] <- Lx$Lb5[i+1]/Lx$Lb5[i]
Lx$sw1[i] <- Lx$Lw1[i+1]/Lx$Lw1[i]
Lx$sw2[i] <- Lx$Lw2[i+1]/Lx$Lw2[i]
Lx$sw3[i] <- Lx$Lw3[i+1]/Lx$Lw3[i]
Lx$sw4[i] <- Lx$Lw4[i+1]/Lx$Lw4[i]
Lx$sw5[i] <- Lx$Lw5[i+1]/Lx$Lw5[i]
}
How I could also create the variable names (letters b and w, and
numbers from 1 to 5 in s and L variables) using a loop in R?
In Stata I can use this command:
foreach r in b w {;
foreach s of numlist 0(5)40 {;
foreach ed of numlist 1/5 {;
local f = `s'+5;
scalar define rL`r'`ed'_`f'over`s' =
L`r'`ed'_`f' / L`r'`ed'_`s';
};
};
};
but I do not how to do it in R.
Thank you in advance!
--
Sebasti?n Daza
Dear Sebastian,
The following will create the names
paste("sb",1:5,sep="")
paste("sw",1:5,sep="")
paste("Lw",1:5,sep="")
paste("Lb",1:5,sep="")
Then you can easily combine and/or order them in R.
Hope this helps.
Ozgur
-----
************************************
Ozgur ASAR
Research Assistant
Middle East Technical University
Department of Statistics
06531, Ankara Turkey
Ph: 90-312-2105309
http://www.stat.metu.edu.tr/people/assistants/ozgur/
--
View this message in context:
http://r.789695.n4.nabble.com/Loop-question-tp4631896p4631900.html
Sent from the R help mailing list archive at Nabble.com.
Note that in R >= 2.15 you can also use paste0 for this operation more efficiently. Michael On Thu, May 31, 2012 at 1:58 AM, ?zg?r Asar <oasar at metu.edu.tr> wrote:> Dear Sebastian, > > The following will create the names > > paste("sb",1:5,sep="") > paste("sw",1:5,sep="") > paste("Lw",1:5,sep="") > paste("Lb",1:5,sep="") > > Then you can easily combine and/or order them in R. > > Hope this helps. > Ozgur > > ----- > ************************************ > Ozgur ASAR > > Research Assistant > Middle East Technical University > Department of Statistics > 06531, Ankara Turkey > Ph: 90-312-2105309 > http://www.stat.metu.edu.tr/people/assistants/ozgur/ > -- > View this message in context: http://r.789695.n4.nabble.com/Loop-question-tp4631896p4631900.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.