[R] applying a function over a matrix 2N x M to produce a matrix N x M

David Winsemius dwinsemius at comcast.net
Fri Apr 22 18:28:23 CEST 2011


On Apr 22, 2011, at 12:13 PM, Christine SINOQUET wrote:

> Hello,
>
> mat1 only consists of 0s and 1s:
> 0 0 1 0 0 0
> 1 1 0 1 1 0
> 1 1 1 0 1 0
> 0 1 1 0 0 1
> 1 0 0 1 0 0
> 0 1 0 1 0 1
>
> N = 3
> M = 6
>
> I would like to "compress" mat1 every two rows, applying summation  
> over the two rows (per column), at each step, to yield:
>
> mat2
> 1 1 1 1 1 0
> 1 2 2 0 1 1
> 1 1 0 2 0 1

 > mat[seq(1, nrow(mat), by=2), ]+mat[seq(2, nrow(mat), by=2), ]
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    1    1    0
[2,]    1    2    2    0    1    1
[3,]    1    1    0    2    0    1

>
> Then, in mat2, I shall have to count the number of 0s, 1s and 2s,  
> per column, which is my final aim.
>
> I am aware of possibilities such as
>
> counts <- sapply(mat2,2,fun1)
>
> but I do not know how to write fun1.
>
>
> Besides, it was perhaps not necessary to waste memory producing the  
> temporary matrix mat2.
>
> Can somebody help ?
>
> I thank you in advance for your answer.
>
> Best regards,
>
> Christine Sinoquet
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list