[R] Deleting rows satisfying a certain condition (sum of some colums>2)

Katie C katie.cheon at gmail.com
Sat Mar 8 06:17:35 CET 2008


I have a huge matrix and need to delete certain rows. What I need to do is:
1.In each row, calculate the sum of jth column and (J+2)th column
2. If the sum is greater than 2 then that row needs to be deleted.

I have a sample matrix and my codes here. It does remove some rows but when
it does, it skips the next row and each time it deletes a row, the dimension
changes so it gets out of bound. I tried to fix those problems but it did
not work. Any suggestions please? Thank you.


S1=c(2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,
1,1,1,1,1,1,2,1,1,0,0,0,2,1,1,0,0,0,2,1,1,0,0,0,2,2,1,2,1,0,2,2,1,2,1,0,2,2,1,2,1,0);

SS=matrix(S1,nrow=18);

nr =dim(SS)[1];
nc =dim(SS)[2]/2;
nt=2;
ms=2;


for (i in 1:nr){
    for (j in 1:nc){
        #print(paste("Sum=",SS[i,j]+SS[i,j+nt],"  ms=",ms));
        if (SS[i,j]+SS[i,j+nt]> ms){ 
        SS=SS[-i,] 
        nr=dim(SS)[1] #this doesn't update nr in the outer for loop. why?
        print(nr) }
    }
   # i=i-1 #this doesn't help to avoid skipping rows   
}
SS;

-- 
View this message in context: http://www.nabble.com/Deleting-rows-satisfying-a-certain-condition-%28sum-of-some-colums%3E2%29-tp15911408p15911408.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list