[R] applying order() in a for loop

Kim Milferstedt milferst at uiuc.edu
Thu Oct 26 22:40:33 CEST 2006


Hi,

with the code below I try to organize sections of a data.frame. The 
dataframe has 9 data columns. I'd like to order the columns of the 
data.frame by the sum of the columns' entries. The sections of the 
columns are identified by "i". The order of the columns is given by 
the vector "z". Each section of the data.frame is ordered 
differently. This can be seen when looking at the individual rows of 
"h" where all different "z" vectors are stored for later use.

In a third for loop, "e" is calculated based on the ordering 
calculated before. "e" is the re-organized data.frame with now all 
column segments in descending order -- in theory.

Problem:
The code below does not update the "z" in the third for loop. It 
remains the initial "z" that I calculate the first time around. I 
tried re-initializing "z" at various places in the code, hoping to 
get rid of the old values but with no apparent consequences. Also in 
the help I could not find anything that I could relate to my problem.

Does anybody have a suggestion on how to get the appropriate "z" to 
work when shuffling the data around for "e"?

Thanks already for suggestions!

Kim

### Code ####

for (i in 11:19)
     {
         for (j in 3:ncol(data))
             {
                 a <- sum(data[,j][data[,1] == i/10])
                 b <- c(b,a)
             }

         z <- order(b, decreasing = TRUE)
         d <- length(data[,1][data[,1] == i/10])

         h <- rbind(h,z) ### Just to check whether I really get 
different orderings for the different data segments.
	
         for (l in 1:d)
             {
                 e <- data[((i-10)*d+l-d),(3:ncol(data))][z] ## This 
z does not get updated but remains the initially calculated z
                 f <- rbind(f,e)
             }
         b <- NULL
         e <- NULL
         z <- NULL
     }



More information about the R-help mailing list