I am a new user of \"R\", and I couldn\'t find a good solution to solve it. I got a timeseries in the following format:
>dates temperature depth salini
I'd add the day, month and year into the data frame and then use aggregate().
First convert your date column into a POSIXct objet:
d$timestamp <- as.POSIXct(d$dates,format = "%m/%d/%Y %H:%M",tz ="GMT")
Then get the date (e.g. 12/03/2012) into a column called Date, try this:
d$Date <- format(d$timestamp,"%y-%m-%d",tz = "GMT")
Next, aggregate by the date:
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ Date,
data = d,
FUN = mean)
Similarly, you can get the month into a column (let's call it M for month), and then...
d$M <- format(d$timestamp,"%B",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ M,
data = d,
FUN = mean)
or if you want year-month
d$YM <- format(d$timestamp,"%y-%B",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ YM,
data = d,
FUN = mean)
If you have any NA values in your data, you may need to account for those:
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ YM,
data = d,
function(x) mean(x,na.rm = TRUE))
Finally, if you want to average by week, you can do that as well. First generate the week number, and then use aggregate() again.
d$W <- format(d$timestamp,"%W",tz = "GMT")
aggregate(cbind("temperature.mean" = temperature,
"salinity.mean" = salinity) ~ W,
data = d,
function(x) mean(x,na.rm = TRUE))
This version of week number defines week 1 as being the week with the first Monday of the year. The weeks are from Monday to Sunday.