如何将带有 YearMonth 列的数据框转换为 R 中的时间序列

How to convert dataframe with YearMonth column to times series in R

我有以下数据集,它是一个数据框。但我想将其转换为时间序列,以便进行 ARIMA 预测。 在 SO 中搜索了各种主题,但找不到 YEARMONTH grain 中的任何类似内容。每个人都在谈论日期字段。但在这里我没有约会。 我正在使用下面的代码,但这会产生错误

dataset <- data.frame(year =c(2017), YearMonth = c(201701,201702,201703,201704), sales = c(100,200,300,400))
library(zoo)
newdataset <- as.ts(read.zoo(dataset, FUN = as.yearmon))

# Error:
# 
#  In zoo(coredata(x), tt) :
#  some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique

我知道它会出错,因为我将年份列作为第一列,它没有唯一值但不确定如何修复它。

任何帮助将不胜感激。

此致, 阿卡什

一个选项是将 YearMonth 转换为一个月的第一个日期并生成 ts

library(zoo)
dataset$YearMonth = as.Date(as.yearmon(as.character(dataset$YearMonth),"%Y%m"), frac = 0)
dataset
#   year  YearMonth sales
# 1 2017 2017-01-01   100
# 2 2017 2017-02-01   200
# 3 2017 2017-03-01   300
# 4 2017 2017-04-01   400

只是为了 ts 另一种选择是:

dataset$YearMonth = as.yearmon(as.character(dataset$YearMonth),"%Y%m")

as.ts(dataset[-1])
# Time Series:
#   Start = 1 
# End = 4 
# Frequency = 1 
# YearMonth sales
# 1  2017.000   100
# 2  2017.083   200
# 3  2017.167   300
# 4  2017.250   400