Skip to content
Prev 275738 / 398506 Next

Simple time series question with zoo

On Thu, Oct 27, 2011 at 4:18 PM, Vinny Moriarty <vwmoriarty at gmail.com> wrote:
That link is several years old.  Since then the zoo package has gained
additional capabilities. Assuming the 2nd field is the desired
date/time and the last field on each line is the one you want try this
read.zoo statement.   See ?read.zoo and also try:
vignette("zoo-read")

library(zoo)
library(chron)

# create test file
Lines <- "line.site,time_local,time_utc,reef_type_code,sensor_type,sensor_depth_m,temp
06,2006-04-09 10:20:00,2006-04-09 20:20:00,BAK,sb39, 2, 29.63
06,2006-04-09 10:40:00,2006-04-09 20:40:00,BAK,sb39, 2, 29.56"
cat(Lines, "\n", file = "data.txt")

# NULL fields are removed


temp <- read.zoo("data.txt", FUN = as.chron, header = TRUE, sep = ",",
	colClasses = c("NULL", NA, "NULL", "NULL", "NULL", "NULL", NA))

# daily
temp.day <- read.zoo("data.txt", FUN = as.Date, header = TRUE, sep = ",",
	aggregate = mean,
	colClasses = c("NULL", NA, "NULL", "NULL", "NULL", "NULL", NA))

# monthly
temp.ym <- read.zoo("data.txt", FUN = as.yearmon, header = TRUE, sep = ",",
	aggregate = mean,
	colClasses = c("NULL", NA, "NULL", "NULL", "NULL", "NULL", NA))

chron represents date/time internally as days since the Epoch +
fraction of day for the time.  Thus truncating to an integer removes
the fractional part (i.e. the time) leaving the day. See R News 4/1.
We could alternately just use the Date class in the base of R as shown
above.

If we had read in temp and wanted to aggregate it rather than read it
straight into an aggregated form then here are some possibilities:

aggregate(temp, trunc, mean) # daily
aggregate(temp, as.Date, mean) # daily with Date class
aggregate(temp, as.yearmon, mean)  # monthly