Skip to content

applying a function over a matrix 2N x M to produce a matrix N x M

4 messages · Christine SINOQUET, Richard M. Heiberger, David Winsemius

#
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

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
#
On Apr 22, 2011, at 12:13 PM, Christine SINOQUET wrote:

            
> 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
David Winsemius, MD
West Hartford, CT
#
On Apr 22, 2011, at 2:38 PM, Richard M. Heiberger wrote:

            
Yawn. Who cares about doubling speed?
Strong work, Richard. I like this answer much better than mine and I  
think it is truly novel. It does what I had thought should be  
possible, but I abandoned that effort and now see my brain was only  
working in two dimensions. Here you are now thinking "inside a  
box" ...  except the box is now 3-dimensional!