2

I need to add two irregular time series (covering business days).

I have two xts series for two different products A + B.

Product B has data from a later startup-date than A.

I think I need to prepend B so that the dates matches A, but with all zeroes.

Such that sum(A + B) equals sum(A) + sum(B)

Product A

2009-05-02  4
2010-02-03  4

Product B

2010-02-03  4

Sum:

A + B
2010-02-03  8

Desired result

2009-05-02  4
2010-02-03  8
tovare
  • 4,027
  • 5
  • 29
  • 30
  • 1
    Can you please post some example data? See http://stackoverflow.com/q/5963269/602276 for tips to write a great question. – Andrie Jun 10 '11 at 08:33

2 Answers2

4

How's this?

library(xts)

Fist we need some sample data.

proda <- as.xts(matrix(c(4,4), ncol = 1, dimnames = list(c("2009-05-02", "2010-02-03"))))
prodb <- as.xts(matrix(4, ncol = 1, dimnames = list(c("2010-02-03"))))

Based on (common) row names, merge will link the two created data sets.

ab <- merge(proda, prodb)

I used apply to sum values per each row (MARGIN = 1) but rowSums would work also.

data.frame(val = apply(X = ab, MARGIN = 1, FUN = sum, na.rm = TRUE))

Result:

           val
2009-05-02   4
2010-02-03   8
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
4

Here's a one-liner (using @Roman's example data):

with(merge(proda,prodb,fill=0), proda+prodb)
#            proda
# 2009-05-02     4
# 2010-02-03     8

merge.xts has all=TRUE as a default and the fill= argument allows you to specify the values to be used for missing elements (default is fill=NA).

The result of merge(proda,prodb,fill=0) is an object with two columns ("proda","prodb") and an index value for every index value in any of the objects passed to merge.xts.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418