【问题标题】:How to unnest samples from a fable R forecast model如何从寓言 R 预测模型中取消嵌套样本
【发布时间】:2020-11-22 23:58:03
【问题描述】:

我正在尝试从使用fable 生成的预测模型中获取样本。这是我尝试过的

library(fable)
library(tsibble)
library(tsibbledata)
library(dplyr)
library(tidyr)

# Forecasting with an ETS(M,Ad,A) model to Australian beer production
beer_fc <- aus_production %>%
  model(ets = ETS(log(Beer) ~ error("M") + trend("Ad") + season("A"))) %>%
  forecast(h = "3 years", bootstrap=TRUE, times = 5)

beer_fc %>% unnest(c(Beer))

我得到的错误是:

Error: Input must be list of vectors

这里是str(beer_fc$Beer[1])的数据结构:

> str(beer_fc$Beer[1])
dist [1:1] 
$ :List of 3
 ..$ dist     :List of 1
 .. ..$ x: num [1:5] 6.09 6.02 6.06 6 5.95
 .. ..- attr(*, "class")= chr [1:2] "dist_sample" "dist_default"
 ..$ transform:function (.x)  
 .. ..- attr(*, "class")= chr "transformation"
 .. ..- attr(*, "inverse")=function (.x)  
 ..$ inverse  :function (.x)  
 ..- attr(*, "class")= chr [1:2] "dist_transformed" "dist_default"
@ vars: chr "Beer"

【问题讨论】:

    标签: r forecasting tidy fable tidyverts


    【解决方案1】:

    如果我们想将 'dist' 值提取为 'long' 格式,循环遍历 list 列 'Beer',提取值,将其分配回 'Beer' 然后unnest

    library(purrr)
    library(tidyr)
    library(dplyr)
    beer_fc$Beer <- map(beer_fc$Beer, ~ .x[[1]]$x)
    beer_fc %>%
           unnest(c(Beer))
    

    -输出

    # A tibble: 60 x 4
    #   .model Quarter  Beer .mean
    #   <chr>    <qtr> <dbl> <dbl>
    # 1 ets    2010 Q3  6.02  402.
    # 2 ets    2010 Q3  5.99  402.
    # 3 ets    2010 Q3  6.05  402.
    # 4 ets    2010 Q3  5.92  402.
    # 5 ets    2010 Q3  5.99  402.
    # 6 ets    2010 Q4  6.15  470.
    # 7 ets    2010 Q4  6.15  470.
    # 8 ets    2010 Q4  6.17  470.
    # 9 ets    2010 Q4  6.17  470.
    #10 ets    2010 Q4  6.12  470.
    # … with 50 more rows
    

    【讨论】:

      【解决方案2】:

      您可以使用pluck 获取要从任何级别提取的值,然后使用unnest。

      library(tidyverse)
      
      beer_fc %>%
        mutate(value = map(Beer, purrr::pluck, 'dist', 'x')) %>%
        unnest(value)
      
      # A tibble: 60 x 5
      #   .model Quarter         Beer .mean value
      #   <chr>    <qtr>       <dist> <dbl> <dbl>
      # 1 ets    2010 Q3 t(sample[5])  402.  6.00
      # 2 ets    2010 Q3 t(sample[5])  402.  6.02
      # 3 ets    2010 Q3 t(sample[5])  402.  5.99
      # 4 ets    2010 Q3 t(sample[5])  402.  6.05
      # 5 ets    2010 Q3 t(sample[5])  402.  5.92
      # 6 ets    2010 Q4 t(sample[5])  483.  6.21
      # 7 ets    2010 Q4 t(sample[5])  483.  6.16
      # 8 ets    2010 Q4 t(sample[5])  483.  6.14
      # 9 ets    2010 Q4 t(sample[5])  483.  6.22
      #10 ets    2010 Q4 t(sample[5])  483.  6.16
      # … with 50 more rows
      

      【讨论】:

        猜你喜欢
        • 2021-02-04
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 2021-09-19
        • 1970-01-01
        • 2020-07-19
        • 2020-12-03
        • 2022-07-29
        相关资源
        最近更新 更多