How to get the sum of each four rows of a matrix in R

Abe picture Abe · Jul 29, 2011 · Viewed 7.2k times · Source

I have a 4n by m matrix (sums at 7.5 min intervals for a year). I would like to transform these to 30 min sums, e.g. convert a 70080 x 1 to a 17520 matrix.

What is the most computationally efficient way to do this?

More specifics: here is an example (shortened to one day instead of one year)

library(lubridate)
start.date <- ymd_hms("2009-01-01 00:00:00")
n.seconds    <- 192 # one day in seconds
time <- start.date + c(seq(n.seconds) - 1) * seconds(450)

test.data <- data.frame(time = time, 
                        observation = sin(1:n.seconds / n.seconds * pi))

R version: 2.13; Platform: x86_64-pc-linux-gnu (64-bit)

Answer

Aaron left Stack Overflow picture Aaron left Stack Overflow · Jul 29, 2011
colSums(matrix(test.data$observation, nrow=4))