【问题标题】:tsibble -- how do you get around implicit gaps when there are nonetsibble - 当没有隐含间隙时,你如何绕过隐含间隙
【发布时间】:2020-04-19 15:56:28
【问题描述】:

我是 tsibble 包的新手。我有每月数据,我强迫一个 tsibble 使用 fable 包。我遇到的一些问题

  • 看起来索引变量(来自我的测试)不是上课日期,即使我申请了 lubridate 的 ymd 函数。
  • has_gaps 函数返回 FALSE,但是当我对数据建模时,我收到“.data 包含的错误” 隐含的时间间隔”
library(dplyr)
library(fable)
library(lubridate)
library(tsibble)

test <- data.frame(
   YearMonth = c(20160101, 20160201, 20160301, 20160401, 20160501, 20160601,
                 20160701, 20160801, 20160901, 20161001, 20161101, 20161201),
      Claims = c(13032647, 1668005, 24473616, 13640769, 17891432, 11596556,
                 23176360, 7885872, 11948461, 16194792, 4971310, 18032363),
     Revenue = c(12603367, 18733242, 5862766, 3861877, 15407158, 24534258,
                 15633646, 13720258, 24944078, 13375742, 4537475, 22988443)
)

test_ts <- test %>% 
  mutate(YearMonth = ymd(YearMonth)) %>% 
  as_tsibble(
    index = YearMonth,
    regular = FALSE       #because it picks up gaps when I set it to TRUE
    )

# Are there any gaps?
has_gaps(test_ts, .full = T)

model_new <- test_ts %>% 
  model(
  snaive = SNAIVE(Claims))
Warning messages:
1: 1 error encountered for snaive
[1] .data contains implicit gaps in time. You should check your data and convert implicit gaps into explicit missing values using `tsibble::fill_gaps()` if required.

任何帮助将不胜感激。

【问题讨论】:

    标签: r time-series tsibble fable


    【解决方案1】:

    您有一个每日索引,但您想要一个每月索引。最简单的方法是使用tsibble::yearmonth() 函数,但您需要先将日期转换为字符。

    library(dplyr)
    library(tsibble)
    
    test <- data.frame(
      YearMonth = c(20160101, 20160201, 20160301, 20160401, 20160501, 20160601,
        20160701, 20160801, 20160901, 20161001, 20161101, 20161201),
      Claims = c(13032647, 1668005, 24473616, 13640769, 17891432, 11596556,
        23176360, 7885872, 11948461, 16194792, 4971310, 18032363),
      Revenue = c(12603367, 18733242, 5862766, 3861877, 15407158, 24534258,
        15633646, 13720258, 24944078, 13375742, 4537475, 22988443)
    )
    
    test_ts <- test %>%
      mutate(YearMonth = yearmonth(as.character(YearMonth))) %>%
      as_tsibble(index = YearMonth)
    

    【讨论】:

    • 非常感谢。这很有帮助。
    【解决方案2】:

    看起来as_tsibble 无法正确识别YearMonth 列中的间隔,因为它是Date 类对象。它隐藏在帮助页面的“索引”部分中,这可能是个问题:

    对于规则间隔的 tbl_ts,必须选择索引表示。例如,每月数据应对应由 yearmonth 或 zoo::yearmon 创建的时间索引,而不是 Date 或 POSIXct。

    就像该摘录表明您可以使用yearmonth() 解决问题。但这需要先对字符串进行一些操作才能将其转换为可以正确解析的格式。

    test_ts <- test %>% 
      mutate(YearMonth = gsub("(.{2})01$", "-\\1", YearMonth) %>% 
               yearmonth()
             ) %>%
      as_tsibble(
        index = YearMonth
      )
    

    现在模型应该可以正常运行了!不知道为什么has_gaps() 测试在您的示例中说一切正常...

    【讨论】:

    • 感谢您的帮助。
    • 小记,1天的间隔适合用日期类表示的月度数据。这是因为月份的天数是不规则的,因此当以每日测量值表示时,最大公分母是一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2016-06-14
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多