[R] grouping rows into bin ranges

Thibaut Jombart jombart at biomserv.univ-lyon1.fr
Mon Oct 22 18:58:23 CEST 2007

```Muri Soares wrote:

>Hi everyone,
>
>I have a matrix that contains 1000 replicates of a sample of a list of values. I want to group each row (row=replicate) into my defined bin ranges and then calculate the mean and stdev for each of the bin ranges (so I will have 1000 rows but ncol=number of bin ranges).
>I don't know how to group rows in a matrix matrix according to another vector (which is what I think I need to do).
>
>Thanks for the help,
>Muri
>
>
>
Hi,

you may try this, once your factor grouping the rows is defined (here
noted 'fac') :

> A=matrix(1:12,ncol=3)
> A
[,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

> fac=factor(c(1,1,2,2))

> split(A,fac)
\$`1`
[1]  1  2  5  6  9 10

\$`2`
[1]  3  4  7  8 11 12

> groupeA = lapply(split(A,fac),matrix,ncol=ncol(A))
> groupeA
\$`1`
[,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10

\$`2`
[,1] [,2] [,3]
[1,]    3    7   11
[2,]    4    8   12

And then you can perform any action on these matrices using lapply or
sapply.

Regards,

Thibaut.

--
######################################
Thibaut JOMBART
CNRS UMR 5558 - Laboratoire de Biométrie et Biologie Evolutive
Universite Lyon 1
43 bd du 11 novembre 1918
69622 Villeurbanne Cedex
Tél. : 04.72.43.29.35
Fax : 04.72.43.13.88
jombart at biomserv.univ-lyon1.fr
http://lbbe.univ-lyon1.fr/-Jombart-Thibaut-.html?lang=en

```