1

I have one zoo object with hourly observations, and one with daily observations. My goal is to merge the two series by the index into one object, where I match daily values with all hourly values of the same date.

To be specific, the first object zX contains hourly observations with no missing values. The second object zY contains a list of certain special dates. These should be added to zX as a dummy on every observation on that day.

library(zoo)

# 3 days of data with hourly resoulution
x <- runif(24*3)
indexHour <- as.POSIXct(as.Date("2015-01-01") + seq(0, (24*3-1)/24, 1/24))
zX <- zoo(x, indexHour)

# Only 2 days of data with daily resolution - one date is missing
y <- c(0, 2)
indexDay <- as.POSIXct(c(as.Date("2015-01-01"), as.Date("2015-01-3")))
zY <- zoo(y, indexDay)

Expected output

2015-01-01 00:00:00 0.78671677  0
2015-01-01 01:00:00 0.40625297  0
... 
2015-01-01 23:00:00 0.75371677  0
2015-01-02 00:00:00 0.34571677  NA
2015-01-02 01:00:00 0.40625297  NA
...
2015-01-02 23:00:00 0.12671677  NA
2015-01-03 00:00:00 0.54671677  2
2015-01-03 01:00:00 0.40625297  2
...
2015-01-03 23:00:00 0.23671677  2
zaphoid
  • 98
  • 7

2 Answers2

0

Try this:

z <- cbind(zX, zY =  coredata(zY)[match(as.Date(time(zX)), as.Date(time(zY)))])

giving:

> head(z, 30)
                            zX zY
2014-12-31 19:00:00 0.20050507  0
2014-12-31 20:00:00 0.98745944  0
2014-12-31 21:00:00 0.02685118  0
2014-12-31 22:00:00 0.82922065  0
2014-12-31 23:00:00 0.77466073  0
2015-01-01 00:00:00 0.87494486  0
2015-01-01 01:00:00 0.39466493  0
2015-01-01 02:00:00 0.49233047  0
2015-01-01 03:00:00 0.19231866  0
2015-01-01 04:00:00 0.91684281  0
2015-01-01 05:00:00 0.48264758  0
2015-01-01 06:00:00 0.08900482  0
2015-01-01 07:00:00 0.48236308  0
2015-01-01 08:00:00 0.30624266  0
2015-01-01 09:00:00 0.48860905  0
2015-01-01 10:00:00 0.18761759  0
2015-01-01 11:00:00 0.37730202  0
2015-01-01 12:00:00 0.51766405  0
2015-01-01 13:00:00 0.30146257  0
2015-01-01 14:00:00 0.66511275  0
2015-01-01 15:00:00 0.66457355  0
2015-01-01 16:00:00 0.92248105  0
2015-01-01 17:00:00 0.17868851  0
2015-01-01 18:00:00 0.71363131  0
2015-01-01 19:00:00 0.82189523 NA
2015-01-01 20:00:00 0.73392131 NA
2015-01-01 21:00:00 0.95409518 NA
2015-01-01 22:00:00 0.49774272 NA
2015-01-01 23:00:00 0.27700155 NA
2015-01-02 00:00:00 0.85833340 NA
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

Inspired by the join statements in How to join (merge) data frames (inner, outer, left, right)? the following code produce desired output:

x <- cbind(x = coredata(zX), date = format(as.Date(index(zX))))
y <- cbind(y = coredata(zY), date = format(as.Date(index(zY))))
z <- zoo(merge(x, y, by = 'date', all.x=TRUE), index(zX))
z <- z[,!colnames(z) %in% c('date')]
View(z)
Community
  • 1
  • 1
zaphoid
  • 98
  • 7