2013-03-11 131 views
3
library(zoo) 
a <- read.zoo(data.frame(t = c(1, 2, 3, 4, 5, 6), v = c(20, 20.5, 21, 20.7, 22, 19.6))) 
b <- read.zoo(data.frame(t = c(1, 1.3, 2.4, 2.7, 5.3, 6, 6.9), v = c(15, 15.2, 11, 20.3, 12, 12.6, 20))) 

merge(a, b)將做合併具有動物園多個不規則的時間系列:R:通過平均

 a b 
1 20.0 15.0 
1.3 NA 15.2 
2 20.5 NA 
2.4 NA 11.0 
2.7 NA 20.3 
3 21.0 NA 
4 20.7 NA 
5 22.0 NA 
5.3 NA 12.0 
6 19.6 12.6 
6.9 NA 20.0 

我需要的是跨ab假設柱v平均表示保持連續之間恆定的值時間樣本:

 a b  **desired output** 
1 20.0 15.0   17.50 
1.3 NA 15.2   17.60 
2 20.5 NA   17.85 
2.4 NA 11.0   15.75 
2.7 NA 20.3   20.40 
3 21.0 NA   20.65 
4 20.7 NA   20.50 
5 22.0 NA   21.15 
5.3 NA 12.0   17.00 
6 19.6 12.6   16.10 
6.9 NA 20.0   19.80 

任何想法?

回答

5
x <- merge(a, b) 
rowMeans(na.locf(x)) 
[1] 17.50 17.60 17.85 15.75 20.40 20.65 20.50 21.15 17.00 16.10 19.80 
+0

很酷,謝謝!!! – nccc 2013-03-11 00:27:29