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;
}
Hi,
Try to use aggregate function
RSiteSearch ("aggregate") #for help
Regards
ML
A Ezhil a ?crit :> 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;
> }
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
--
Mohamed Lajnef
INSERM Unit? 955.
40 rue de Mesly. 94000 Cr?teil.
Courriel : Mohamed.lajnef at inserm.fr
tel. : 01 49 81 31 31 (poste 18470)
Sec : 01 49 81 32 90
fax : 01 49 81 30 99
Hi, On Mon, Sep 7, 2009 at 11:46 AM, A Ezhil<ezhil02 at yahoo.com> wrote:> 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.The dlply function in the plyr library provides a very easy and intuitive way to do this ... if you're having problems using it, please post a small representative matrix of your data that we can paste into our own R session to slice and dice for you as an example. -steve -- Steve Lianoglou Graduate Student: Computational Systems Biology | Memorial Sloan-Kettering Cancer Center | Weill Medical College of Cornell University Contact Info: http://cbio.mskcc.org/~lianos/contact