Ray
Ray

Reputation: 3225

Average two Zoo vectors with same index?

Suppose I have two 'zoo' vectors, of equal length, with the same indices for both.

Is there a simple function that allows me to take the average of both, by date (index)?

Thanks!

Upvotes: 1

Views: 670

Answers (2)

Joshua Ulrich
Joshua Ulrich

Reputation: 176668

I don't believe there's a function, but it's pretty easy to do with apply:

set.seed(21)
z1 <- zoo(rnorm(10), Sys.Date()-10:1)
z2 <- zoo(rnorm(10), Sys.Date()-10:1)
z <- merge(z1,z2)
z$z3 <- apply(z,1,mean)

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368271

Here is one solution which just adds both and divides by 2:

R> a <- zoo(1:10, Sys.Date()+0:9)
R> b <- zoo(10:1, Sys.Date()+0:9)
R> z <- (a + b) / 2
R> merge(a, b, z)
            a  b   z
2011-07-06  1 10 5.5
2011-07-07  2  9 5.5
2011-07-08  3  8 5.5
2011-07-09  4  7 5.5
2011-07-10  5  6 5.5
2011-07-11  6  5 5.5
2011-07-12  7  4 5.5
2011-07-13  8  3 5.5
2011-07-14  9  2 5.5
2011-07-15 10  1 5.5
R> 

Upvotes: 4

Related Questions