Calculation of daily average in R

Let's say I have the following matrix:

x1 = 1:288 x2 = matrix(x1,nrow=96,ncol=3) 

Is there an easy way to get the average value of rows 1: 24.25: 48.49: 72.73: 96 for column 2?

Basically, I have one year, and I have to average some data every 24 hours.

+7
source share
3 answers

Exists.

Suppose we have days:

 Days <- rep(1:4,each=24) 

you can easily do

 tapply(x2[,2],Days,mean) 

If you have a dataframe with a Date variable, you can use it. You can do this for all variables at once using aggregate:

 x2 <- as.data.frame(cbind(x2,Days)) aggregate(x2[,1:3],by=list(Days),mean) 

Take a look at the help files for these features to get started. Also do a search here, there are quite a few other interesting answers to this problem:

PS: If you are going to do a lot of time, you should take a look at the zoo package (on CRAN: http://cran.r-project.org/web/packages/zoo/index.html )

+8
source

1) ts. Since this is a regular time series, convert it to the ts series, and then combine it from frequency 24 to frequency 1:

 > aggregate(ts(x2[, 2], freq = 24), 1, mean) 

giving:

 Time Series: Start = 1 End = 4 Frequency = 1 [1] 108.5 132.5 156.5 180.5 

2) the zoo. It uses a zoo. The zoo package can also handle irregularly spaced rows (if we need to expand it). Below day.hour is the day number (1, 2, 3, 4) plus an hour as part of the day, so floor(day.hour) is just the day number:

 > library(zoo) > day.hour <- seq(1, length = length(x2[, 2]), by = 1/24) > z <- zoo(x2[, 2], day.hour) > aggregate(z, floor, mean) 1 2 3 4 108.5 132.5 156.5 180.5 

If zz is the result, then coredata(zz) and time(zz) are values ​​and times, respectively, like regular vectors.

+4
source

A fairly compact and computationally fast way to do this is to rearrange the vector into a suitable matrix and calculate the means of the column.

 colMeans(matrix(x2[,2],nrow=24)) 
+2
source

All Articles