Skip to content

Combining XTS objects with unmatched but regular dates

3 messages · Worik, Jeff Ryan

#
I have two xts objects
 > head(a)
                   a
2008-12-30 16061.73
2009-01-29 14709.56
2009-02-26 13148.36
2009-03-30 14298.04
2009-04-29 15665.30
2009-05-28 16540.47
 > head(b)
               b
2008-12-31 0.13
2009-01-31 0.30
2009-02-28 0.21
2009-03-31 0.16
2009-04-30 0.18
2009-05-31 0.18

I would like to merge them combining the entries on common dates.  Just 
removing the days would be enough.

 > head(merge(a,b))
                   a    b
2008-12-30 16061.73   NA
2008-12-31       NA 0.13
2009-01-29 14709.56   NA
2009-01-31       NA 0.30
2009-02-26 13148.36   NA
2009-02-28       NA 0.21

That is no good.

How can I do this?

cheers
Worik
#
I should have thought harder...

c <- merge(xts(as.numeric(a), as.Date(timeLastDayInMonth(index(a)))), 
xts(as.numeric(b), as.Date(timeLastDayInMonth(index(b)))))


I moved the indexes to the last day of the month...
as.Date(timeLastDayInMonth(index(a)))

cheers
Worik
On 18/08/10 16:34, Worik wrote:

  
    
#
Merging inconsistent dates is obviously 'tricky' at best.  Since you
are no longer using your data, but rather altering it.

An option or four you can consider:

# note that to_period is a experimental version of to.period that is
temporarily renamed to allow
# for testing.  It is exported in the CRAN xts, and is much faster
(300x) than the old version. It
# also supports OHLC=FALSE.
a    b
2008-12-31 16061.73 0.13
2009-01-31 14709.56 0.30
2009-02-28 13148.36 0.21
2009-03-31 14298.04 0.16
2009-04-30 15665.30 0.18
2009-05-31 16540.47 0.18

# using the dates from 'a'
a    b
2008-12-30 16061.73 0.13
2009-01-29 14709.56 0.30
2009-02-26 13148.36 0.21
2009-03-30 14298.04 0.16
2009-04-29 15665.30 0.18
2009-05-28 16540.47 0.18

# using the dates from 'b'.  Alternately you could call merge.xts
explicitly: > merge.xts(coredata(a),b)
 > merge(b,coredata(a))[,2:1]
                  a    b
2008-12-31 16061.73 0.13
2009-01-31 14709.56 0.30
2009-02-28 13148.36 0.21
2009-03-31 14298.04 0.16
2009-04-30 15665.30 0.18
2009-05-31 16540.47 0.18

And finally:
a    b
2008-12-31 16061.73 0.13
2009-01-31 14709.56 0.30
2009-02-28 13148.36 0.21
2009-03-31 14298.04 0.16
2009-04-30 15665.30 0.18
2009-05-31 16540.47 0.18

Of course there are many, many more ways to do this...

HTH
Jeff
On Tue, Aug 17, 2010 at 11:34 PM, Worik <worik.stanton at gmail.com> wrote: