
Untitled
By: a guest on
Aug 10th, 2012 | syntax:
None | size: 1.86 KB | hits: 5 | expires: Never
how to add a missing dates and remove repeated dates in hourly time series
date Rainfall(mm)
1970-01-05 00:00:00 1.0
1970-01-05 01:00:00 1.0
1970-01-05 05:00:00 3.6
1970-01-05 06:00:00 3.6
1970-01-05 07:00:00 2.2
1970-01-05 08:00:00 2.2
1970-01-05 09:00:00 2.2
1970-01-05 10:00:00 2.2
1970-01-05 11:00:00 2.2
1970-01-05 13:00:00 2.2
1970-01-05 13:00:00 2.2
1970-01-05 13:00:00 2.2
# Create a sample data.frame missing every second observation.
df <- data.frame(date=seq.POSIXt(from=as.POSIXct("1970-01-01 00:00:00"), to=as.POSIXct("1970-01-01 10:00:00"), by="2 hours"), rainfall=rnorm(6))
#Create a seq of times without anything missing
grid. <- data.frame(date=seq.POSIXt(as.POSIXct("1970-01-01 00:00:00"), to=as.POSIXct("1970-01-01 10:00:00"), by="1 hours"))
# Merge them together keeping all the values from grid.
dat. <- merge(grid., df, by="date", all.x=TRUE)
# The ! means the reverse logic. Therefore TRUE becomes FALSE.
dup_index <- !duplicated(dat.[,1])
# Now re-create the dat. object with only non-duplicated rows.
dat. <- dat.[dup_index,]
dat. <- aggregate(dat.[,2], by=list(dat[,1]), FUN=mean)
Lines <- "date Rainfall(mm)
1970-01-05 00:00:00 1.0
1970-01-05 01:00:00 1.0
1970-01-05 05:00:00 3.6
1970-01-05 06:00:00 3.6
1970-01-05 07:00:00 2.2
1970-01-05 08:00:00 2.2
1970-01-05 09:00:00 2.2
1970-01-05 10:00:00 2.2
1970-01-05 11:00:00 2.2
1970-01-05 13:00:00 2.2
1970-01-05 13:00:00 2.2
1970-01-05 13:00:00 2.2"
library(zoo)
library(chron)
asChron <- function(d, t) as.chron(paste(d, t))
z <- read.zoo(text = Lines, skip = 1, index = 1:2, FUN = asChron, agg = mean)
merge(z, zoo(, seq(start(z), end(z), 1/24))) # as in FAQ