[R] Loop question

Sebastián Daza sebastian.daza at gmail.com
Thu May 31 05:28:01 CEST 2012


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


More information about the R-help mailing list