You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何正确展开data frame的distribution类型列?

在R中如何正确展开fable里的distribution类型列?

我需要用forecast()生成预测结果,但它返回的fable对象里包含distribution类型的列,而我需要把它展开成类似generate()输出的长格式(便于绘图)。我自己用map()+pivot_longer()实现了,但感觉不是最优解,想知道正确的处理方式。

示例数据与原实现

library(fpp3)

gafa_stock |>
  filter(Symbol == "GOOG", year(Date) >= 2015) |>
  mutate(day = row_number()) |>
  update_tsibble(index = day, regular = TRUE) ->
  google_stock

google_stock |> filter(year(Date) == 2015) -> google_2015

google_2015 %>% model(NAIVE(Close)) -> fit

# 理想的长格式输出(来自generate)
fit %>% generate(h = 30, times = 5, bootstrap = TRUE) -> gen.sim

# 带distribution列的预测结果(来自forecast)
fit %>% forecast(h = 30, times = 5, bootstrap = TRUE) -> fcs.sim

# 我自己的手动处理方式
fcs.sim %>% 
  pull(Close) %>% 
  map(unlist) %>% 
  bind_rows() %>% 
  bind_cols(fcs.sim) %>% 
  pivot_longer(cols=x1:x5) %>% 
  mutate(name=str_remove(name,'^x')) %>% 
  rename(.rep=name) ->
  fcs.sim.2.gen.sim

最优解法:使用unpack_distribution()

fpp3生态的fable包提供了专门处理distribution类型列的函数unpack_distribution(),可以一步完成展开,无需手动拼接和列名调整:

# 一键展开distribution列
fcs.sim %>%
  unpack_distribution(Close, .rep = TRUE) %>%
  rename(.sim = Close) -> fcs.sim.unpacked

这个函数会自动把Close列中的样本展开为多行,同时生成.rep列标记样本编号,最终输出格式和generate()完全一致,直接可用于绘图或后续分析。

最终输出效果

# # A tsibble: 150 x 5 [1]
# # Key:       Symbol, .model, .rep [5]
# Symbol .model       .rep    day  .sim
# <chr>  <chr>        <chr> <dbl> <dbl>
# 1 GOOG   NAIVE(Close) 1       253  752.
# 2 GOOG   NAIVE(Close) 1       254  758.
# 3 GOOG   NAIVE(Close) 1       255  761.
# 4 GOOG   NAIVE(Close) 1       256  750.

内容的提问来源于stack exchange,提问作者lowndrul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:23:12