【发布时间】:2019-02-27 10:47:02
【问题描述】:
我有一个数据框,其中包含一个时间序列的月度数据,其中有一些缺失值。
dates <- seq(
as.Date("2010-01-01"), as.Date("2017-12-01"), "1 month"
)
n_dates <- length(dates)
dates <- dates[runif(n_dates) < 0.5]
time_data <- data.frame(
date = dates,
value = rnorm(length(dates))
)
## date value
## 1 2010-02-01 1.3625419
## 2 2010-06-01 0.1512481
## etc.
为了能够在 forecast 等中使用时间序列预测功能,我想将其转换为 ts 对象。
执行此操作的愚蠢方法是在整个时间段内创建一组定期的每月日期,然后将左连接返回到原始数据。
library(dplyr)
first_date <- min(time_data$date)
last_date <- max(time_data$date)
full_dates <- data.frame(
date = seq(first_date, last_date, "1 month")
)
extended_time_data <- left_join(full_dates, time_data, by = "date")
## date value
## 1 2010-02-01 1.3625419
## 2 2010-03-01 NA
## etc.
现在我可以使用ts() 创建时间序列。
library(lubridate)
time_series <- ts(
extended_time_data$value,
start = c(year(first_date), month(first_date)),
frequency = 12
)
对于这样一个简单的任务,这是冗长而粗暴的。
我还研究过首先转换为xts,并使用timetk 包中的转换器,但没有什么比我更简单的方法了。
这个问题是How to create time series with missing datetime values的骗子,但那里的答案更模糊。
如何根据缺少值的时间序列创建 ts 对象?
【问题讨论】:
-
什么是
n_dates试试expandtime_data %>% expand(date = seq(min(date),max(date), by = "1 month"), select(., everything(), -date)) -
我认为
n_dates应该是length(seq( as.Date("2010-01-01"), as.Date("2017-12-01"), "1 month" )) -
您还缺少
lubridate包来访问您的示例代码中的year/month等。
标签: r time-series missing-data