Joyce
Joyce

Reputation: 2687

Merge two zoo objects with data summed up for column with same names

I would like to merge two zoo objects, with data summed up if the column names are the same.For example,

ZooObject1
Date A B C
1/1/2012 2 4 8
1/2/2012 1 3 9
1/3/2012 3 6 4

ZooObject2
Date D B E
1/1/2012 3 4 9
1/2/2012 2 7 2
1/3/2012 1 8 8

MergedObject
Date A B C D E
1/1/2012 2 8 8 3 9
1/2/2012 1 10 9 2 2
1/3/2012 3 14 4 1 8

In this case, since both ZooObject1 and ZooObject2 has column named "B", the figures of column B in the merged zoo object will be sum of figures of "B" in ZooObject1 and that of "B" in ZooObject2

Any simple code can achieve this?

Upvotes: 1

Views: 627

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269501

Calculate the common names and the names unique to each input and then put it all together fixing up any mangled names:

both <- intersect(names(z1), names(z2))
only1 <- setdiff(names(z1), both)
only2 <- setdiff(names(z2), both)

setNames(cbind(z1[, only1], z2[, only2], z1[, both] + z2[, both]),
    c(only1, only2, both))

This works at least on the sample input. There may or may not need to be some changes if your actual problem varies from it in some important way.

Upvotes: 4

seancarmody
seancarmody

Reputation: 6290

It's not beautiful, but this will do the job:

library(reshape2)
z <- merge(ZooObject1, ZooObject2)
z <- melt(cbind(data.frame(t=time(z)), as.data.frame(z)), id.vars="t")
z$variable <- gsub("\\..*$", "", z$variable)
z <- dcast(z, t ~ variable, fun.aggregate=sum)
z <- zoo(z[,-1], z[,1])

For zoo objects, the time index must be unique, so this approach converts the zoo objects back to data frames, with the time index as a column, aggregates and then converts the results back to a zoo object. It's not bullet proof: if the field names in your zoo objects have . in their names, it will break!

Upvotes: 1

Related Questions