Pergunta

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
Foi útil?

Solução

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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top