Skip to content

Simple time series question with zoo

3 messages · Vinny Moriarty, Gabor Grothendieck, Marc Girondot

#
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
#
Le 27/10/11 22:18, Vinny Moriarty a ?crit :
> strsplit("2006-04-09 10:20:00", " ")[[1]][1]
[1] "2006-04-09"
 > strsplit("2006-04-09 10:20:00", " ")[[1]][2]
[1] "10:20:00"

Then replace with

z<-zoo(LTER6$temp, chron(strsplit(chron(LTER6$DateTime, " ")[[1]][1], strsplit(LTER6$DateTime, " ")[[1]][2]))
Don't know
Explanation (but not still a solution for month aggregate)
The numerical coding format for date-time is that integer part is the 
number of days since a reference and the decimal part is the time. Then 
if you use trunc, two different times of the same day will be identical.