I like David's answer and it can be made much faster.
I show three refinements, each faster than the preceding one.

Rich

> system.time(for (i in 1:1000)
+   mat[seq(1, nrow(mat), by=2), ]+mat[seq(2, nrow(mat), by=2), ]
+ )
   user  system elapsed
   0.18    0.00    0.19
>
> system.time(for (i in 1:1000)
+   mat[seqn <- seq(1, nrow(mat), by=2), ]+mat[seqn+1, ]
+ )
   user  system elapsed
   0.08    0.00    0.08
>
> system.time(for (i in 1:1000)
+   mat[seqn <- seq(1, length=nrow(mat)/2, by=2), ]+mat[seqn+1, ]
+ )
   user  system elapsed
   0.05    0.00    0.05
>
> system.time(for (i in 1:1000)
+   {mat2 <- mat; dim(mat2) <- c(2,3,6); mat2[1,,]+mat2[2,,]}
+ )
   user  system elapsed
   0.01    0.00    0.02
>

On Fri, Apr 22, 2011 at 12:28 PM, David Winsemius <dwinsemius@comcast.net>wrote:

>
> 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
>
>
>

	[[alternative HTML version deleted]]

