簡體   English   中英

如何將數據幀轉換為R中的每小時時間序列

[英]how to convert dataframe into hourly time series in R

我在R中有以下數據框

   hourly_calls                 total_calls
   2017-12-01 08:00-08:59       39
   2017-12-01 09:00-09:59       29
   2017-12-01 10:00-10:59       57
   2017-12-01 11:00-11:59       90
   2017-12-01 12:00-12:59       23
   2017-12-01 13:00-13:59       45
   2017-12-01 14:00-14:59       54
   2017-12-01 15:00-15:59       39
   2017-12-01 16:00-16:59       29
   2017-12-01 17:00-17:00       27
   2017-12-04 08:00-08:59       49
   2017-12-04 09:00-09:59       69
   2017-12-04 10:00-10:59       27
   2017-12-04 11:00-11:59       60
   2017-12-04 12:00-12:59       23
   2017-12-04 13:00-13:59       85
   2017-12-04 14:00-14:59       14
   2017-12-04 15:00-15:59       39
   2017-12-04 16:00-16:59       59
   2017-12-04 17:00-17:00       67

這是呼叫中心每小時呼叫量的數據幀(每周9天輪班/ 5天)。 我想將此數據幀轉換為每小時的時間序列,以便可以預測下幾個小時。

這就是我的做法

 train <- df[1:1152,]
 test < df[1153:1206,]
 train <- msts(train[['total_calls']], seasonal.periods=c(9))
 test <- msts(test[['total_calls']], seasonal.periods=c(9))

我如何在R中做到這一點?

數據中的主要問題是,第一列hourly_calls代表時間范圍,而不僅僅是時間。 因此,它不會自動轉換為date-time以准備ts 一種選擇是只考慮“ Start Time部分並准備時間序列。

library(tidyverse)
library(lubridate)
library(xts)
library(forecast)


#Get the start time first
data <- df %>% extract(hourly_calls, 
c("StartTm", "EndTm"), regex = "(^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})-(\\d{2}:\\d{2})") %>%
  mutate(StartTm = ymd_hm(StartTm))

#Only StartTm has been considered for this  
xtsData <- xts(data$total_calls, order.by = data$StartTm)

train <- xtsData[1:1152,]
test <- xtsData[1153:1206,]

trainTS <- ts(train, freq=9) #9 hours a day
fit <- tslm(trainTS ~ season + trend) 

forecast(fit, newdata = data.frame(x=test))

數據:

df <- read.table(text =
"hourly_calls                 total_calls
'2017-12-01 08:00-08:59'       39
'2017-12-01 09:00-09:59'       29
'2017-12-01 10:00-10:59'       57
'2017-12-01 11:00-11:59'       90
'2017-12-01 12:00-12:59'       23
'2017-12-01 13:00-13:59'       45
'2017-12-01 14:00-14:59'       54
'2017-12-01 15:00-15:59'       39
'2017-12-01 16:00-16:59'       29
'2017-12-01 17:00-17:00'       27
'2017-12-04 08:00-08:59'       49
'2017-12-04 09:00-09:59'       69
'2017-12-04 10:00-10:59'       27
'2017-12-04 11:00-11:59'       60
'2017-12-04 12:00-12:59'       23
'2017-12-04 13:00-13:59'       85
'2017-12-04 14:00-14:59'       14
'2017-12-04 15:00-15:59'       39
'2017-12-04 16:00-16:59'       59
'2017-12-04 17:00-17:00'       67",
header = TRUE, stringsAsFactors = FALSE)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM