0

I have two zoo time series with the same parameters for an area but from different platforms. These two time series have a slight shift in figures even their individual trends are correct and have overlapping dates. I will like to merge both time series into one continuous series while adjusting for errors in both series using the data for the dates that overlap. How do I do this please? I have added some sample data below.

library(ggplot2)
library(gtable)
library(grid)
library(zoo)
library(reshape)
library(reshape2)
##Create zoo objects
x<-as.zoo(as.matrix(cbind(a=1:8,b=2:9)))
y<-as.zoo(as.matrix(cbind(a=2:9,b=3:10)))
##Create dates
CCnb1<-seq(from=as.Date("2004-01-01"),to=as.Date("2004-08-01"),by="1 months")
CCnb2<-seq(from=as.Date("2004-06-01"),to=as.Date("2005-01-01"),by="1 months")
##Index appropriately
index(x)<-CCnb1
index(y)<-CCnb2
####Create dataframes
x1<-as.data.frame(x)
y1<-as.data.frame(y)
##Add date columns
x1$Date=CCnb1
y1$Date=CCnb2
##Melt data frames
x2<-melt(x1, id.vars="Date")
y2<-melt(y1, id.vars="Date")

I have included a pseudo plot using ggplot2 of how the lines might look. My actual time series are much longer and the shift in values isn't as bad as this example.

#Plot
NT<-ggplot(x2, aes(x=Date, y=value,colour=variable, group=variable)) +
theme_bw()+ geom_line(size=0.5,colour="grey30")
NTb<-NT + geom_line(data=y2,aes(x=Date, y=value,group=variable))
NTb+facet_wrap(~variable)

PLot showing the time series above

Joke O.
  • 515
  • 6
  • 29

1 Answers1

1

The difference is constant:

> y$a - x$a
2004-06-01 2004-07-01 2004-08-01 
        -4         -4         -4 
> y$b - x$b
2004-06-01 2004-07-01 2004-08-01 
        -4         -4         -4 

so assuming that x$a is to be adjusted to y$a and simliarly for x$b and y$b:

va <- apply(merge(x$a + coredata(y$a - x$a)[1], y$a), 1, mean, na.rm = TRUE)
a <- zoo(va, as.Date(names(va)))


vb <- apply(merge(x$b + coredata(y$b - x$b)[1], y$b), 1, mean, na.rm = TRUE)
b <- zoo(vb, as.Date(names(vb)))

merge(a, b)

giving:

            a  b
2004-01-01 -3 -2
2004-02-01 -2 -1
2004-03-01 -1  0
2004-04-01  0  1
2004-05-01  1  2
2004-06-01  2  3
2004-07-01  3  4
2004-08-01  4  5
2004-09-01  5  6
2004-10-01  6  7
2004-11-01  7  8
2004-12-01  8  9
2005-01-01  9 10
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341