I have the following matrix of depth and temperature data (855 rows, 2 col) and would like to take the mean of every 3 rows within each column. For example:
Use rollapply function from zoo package. See ?rollapply for more details.
library(zoo)
rollapply(matrix[,1], width=3, mean, by=3)
Example:
> set.seed(1)
> Data <- matrix(rnorm(30, 100, 50), ncol=2) # some random data
> rollapply(Data[,1], width=3, mean, by=3)
[1] 78.69268 118.40534 130.02559 126.60393 71.48317
> # you could check this out by doing some verification as in:
> mean(Data[1:3, 1])
[1] 78.69268
> mean(Data[4:6, 1])
[1] 118.4053
> mean(Data[7:9, 1]) # and so on ...
[1] 130.0256
If you want the mean for all columns in your matrix, then just add by.column=TRUE in the rollapply call:
> rollapply(Data, width=3, mean, by=3, by.colum=TRUE)
[,1] [,2]
[1,] 78.69268 114.71187
[2,] 118.40534 138.90166
[3,] 130.02559 81.12249
[4,] 126.60393 106.79836
[5,] 71.48317 74.48399