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

From: Richard M. Heiberger <rmh_at_temple.edu>
Date: Fri, 22 Apr 2011 14:38:08 -0400

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

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. Received on Fri 22 Apr 2011 - 18:44:19 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 22 Apr 2011 - 19:50:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.