[R] Averaging rows if a condition is true.

A Ezhil ezhil02 at yahoo.com
Mon Sep 7 17:46:45 CEST 2009


Dear All,

I have matrix (50000 X 60) of subjects and their responses to a set of questions. All responses are classified into categories (500). I would like to average all subject's responses for each category. I wrote a code using a for loop but is not working. Could please tell me what's wrong with the code? I guess, there is a elegant R way of doing the same thing.

Thanks in advance.

Kind regards,
Ezhil


j <- 1; n <- dim(dat)[1]; cat <- as.character(dat[,1]);
row <- matrix(nrow=nrow(dat), ncol=ncol(dat));
for(i in 1:n-1) {
  if(cat[i] != cat[i+1]) {row[j, ] <- dat[j, ]}
  else {
      start <- j;
      end <- i;
      }
      row[j, ] <- colMeans(dat[j:i, ]);
      j+1;
  }




More information about the R-help mailing list