Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 773
Abe Avatar asked Jul 29 '11 13:07

Abe


People also ask

How do you calculate the sum of each row in a matrix in R?

The rowSums() function in R can be used to calculate the sum of the values in each row of a matrix or data frame in R. where: x: Name of the matrix or data frame.

Which of the following functions is used to find the sum of the rows across all the matrices?

rowSums() function in R Language is used to compute the sum of rows of a matrix or an array.


2 Answers

sapply(split(test.data$observation, rep(1:(192/4), each=4)), sum)
like image 73
Backlin Avatar answered Oct 12 '22 01:10

Backlin


colSums(matrix(test.data$observation, nrow=4))
like image 37
Aaron left Stack Overflow Avatar answered Oct 12 '22 01:10

Aaron left Stack Overflow