Loop multiple variables in R

for (j in 4:10) { 
     mean[,j-3] <- tapply(gayreshaped[,j],gayreshaped$group, mean) 
     sd[,j-3] <- tapply(gayreshaped[,j], gayreshaped$group, sd)

gayreshaped is a data.frame. group is a variable with 4 values. mean & sd are 4*7 matrices filled with NA.

I want to loop through 7 variables by specifying each column, and fill in the matrices by columns. However, when I run this code, only the first column has been filled.

The result of mean:

          Wave1 Wave2 Wave3 Wave4 Wave5 Wave6 Wave7
group1 3.130975    NA    NA    NA    NA    NA    NA
group2 3.013474    NA    NA    NA    NA    NA    NA
group3 3.025195    NA    NA    NA    NA    NA    NA
group4 3.099710    NA    NA    NA    NA    NA    NA

I don't know what is going on here. Could anyone tell me? Thank you!

0 Comment



Captcha image