R - 使用 zoo 包近似缺失的月份值

R - approximate missing month values using zoo package

考虑代码:

library('zoo')

data <- c(1, 2, 4, 6)
dates <- c("2016-11-01", "2016-12-01", "2017-02-01", "2017-04-01");
z1 <- zoo(data, as.yearmon(dates))
z2 <- na.approx(z1)

变量 z2 看起来像这样:

nov 2016 dec 2016 feb 2017 apr 2017 
       1        2        4        6 

但我需要z2与此类似:

nov 2016 dec 2016 jan 2017 feb 2017 mar 2017 apr 2017 
       1        2        3        4        5        6

我只需要估算缺失值的月份的近似值。感谢您的任何提示。

仅使用 na.approx 和基数 R 的一种方法:

#add your data and dates together
df <- data.frame(data, dates = as.Date(dates))
#create all dates using seq
new_dates <- data.frame(dates = seq(as.Date(dates[1]), as.Date(dates[4]), by = 'month'))
#merge the two and then na.approx
new_df <- merge(new_dates, df, by = 'dates', all.x = TRUE)
na.approx(new_df$data)

输出:

[1] 1 2 3 4 5 6

使用新的 as.zoo 参数 calendar,在 zoo 1.8 中(默认为 TRUE,因此我们不必指定)我们可以将输入转换为 "ts" 然后回到 "zoo" 之后再次应用 na.approx

na.approx(as.zoo(as.ts(z2)))
## Nov 2016 Dec 2016 Jan 2017 Feb 2017 Mar 2017 Apr 2017 
##        1        2        3        4        5        6 

对于以前版本的动物园,我们可以做同样的事情,但手动将索引转换回 "yearmon":

na.approx(aggregate(as.zoo(as.ts(z2)), as.yearmon, c))

magrittr

使用zoo和magrittr可以分别表示为以下流水线:

library(magrittr)

z2 %>% as.ts %>% as.zoo %>% na.approx

z2 %>% as.ts %>% as.zoo %>% aggregate(as.yearmon, c) %>% na.approx