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!
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>
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)
精彩评论