R - 日期分配问题 - 如何更正?

R - Date assignation issue - How to correct it?

我在尝试赋值时遇到问题。 这看起来很奇怪,因为在我将相同的命令应用于另一个数据集后,它起作用了。

下面是一些截图:

数据集 #1 第 1 步:加载数据集 1 并使用 ts 函数。

第 2 步:基于数据集 1 创建一个新对象并重新格式化日期。 (创建错误)

数据集 #2 第 1 步:加载数据集 1 并使用 ts 函数。

第 2 步:基于数据集 1 创建一个新对象并重新格式化日期。 (正确创建)

下面是上面显示的正确代码:

# Load required libraries
library(forecast)
library(lubridate)
library(tidyverse)
library(scales)
library(ggfortify)

# Load historical SLA definitions
bwi <- read.csv(file="C:/Users/nsoria/Documents/Data Science/SLA Prediction/TEC_BWI.csv", header=TRUE, sep=';', dec=",")

# Create time series object
ts_bwi <- ts(bwi$SLA, frequency = 12, start = c(2015,1))

############################################ STL Model Algorithm
# Pull out the seasonal, trend, and irregular components from the time series
model_stl <- stl(ts_bwi, s.window = "periodic")

############################################ ARIMA Model Algorithm
# Pull out the seasonal, trend, and irregular components from the time series
#model_arima <- auto.arima(ts_bwi)

# Predict the next 5 month of SLA (STL)
pred <- forecast(model_stl, h = 5)

# Predict the next 5 month of SLA (ARIMA)
#pred <- forecast(model_arima, h = 5)

# Convert pred from list to data frame object
df1 <- fortify(pred) %>% as_tibble()

# Convert ts decimal time to Date class
df1$Date <- as.Date(date_decimal(df1$Index), "%Y-%m-%d")

这是失败数据集的 link

谢谢。 尼古拉斯.

它正在做你要求它做的事情。

"wrong" df1$Index 已经是一个日期。您无需将其转换为任何内容。当你这样做时,尤其是他们按照你的方式去做时,有趣的事情就会发生。

date_decimal 函数需要一个像 2015.123 这样的数字,并给你“2015-02-14 21:28:48 UTC”。

如果你做了一些疯狂的事情,比如:

date_decimal(as.Date("2015-01-01"))

然后它首先将 as.Date("2015-01-01") 视为它实际的数字(16436,即自 1970 年 1 月 1 日以来的天数)然后它给你 16436-01-01,(即到底是什么你问的。)

您的解决方案是注意到您已经有一个日期,所以没有什么可以转换成日期。

此外,您的代码正在向您发出警告。不要忽略警告。