【问题标题】:Nest Time-Series object into a DataFrame将时间序列对象嵌套到 DataFrame 中
【发布时间】:2017-11-02 19:43:32
【问题描述】:
library(fpp)
library(purrr)
library(tidyr)

data(austourists)
tr <- window(austourists,end=c(2007,12))
te <- window(austourists, start=c(2008,1))

我有 FPP 包中的澳大利亚游客数据。我想创建多个时间序列对象,这些对象根据不同的起始年份进行修剪。

df <- as.data.frame(1999:2005)
colnames(df) <- "yr_start"
df$yr_end <- 2008

我想重复上面看到的窗口函数,但使用df 中的给定输入。我试图使用mapnest 创建一个时间序列对象并将其嵌套到位。

我的目标是一个结构为

的数据框
   head(df)
 yr_start yr_end  ts.object 
 <num>    <num>    <list>
 1992     2008     <S3 class: ts object>
 1993     2008     <S3 class: ts object>
 1994     2008    <S3 class: ts object>
 1995     2008    <S3 class: ts object>
 1996     2008    <S3 class: ts object>
 1997     2008    <S3 class: ts object>

目标是稍后使用这些 ts 对象在这些 ts 对象上使用 map 函数运行指数平滑模型。

【问题讨论】:

    标签: r dataframe tidyr tidyverse purrr


    【解决方案1】:

    您可以在yr_startyr_end 列上使用map2,并为每对start-end 年构造一个ts 对象:

    df %>% 
        mutate(ts.object = map2(yr_start, yr_end, ~ window(austourists, start=c(.x, 1), end=c(.y, 4)))) %>% 
        as.tibble()
    
    # A tibble: 7 x 3
    #  yr_start yr_end ts.object
    #     <int>  <dbl>    <list>
    #1     1999   2008  <S3: ts>
    #2     2000   2008  <S3: ts>
    #3     2001   2008  <S3: ts>
    #4     2002   2008  <S3: ts>
    #5     2003   2008  <S3: ts>
    #6     2004   2008  <S3: ts>
    #7     2005   2008  <S3: ts>
    

    df_ts <- df %>% 
        mutate(ts.object = map2(yr_start, yr_end, ~ window(austourists, start=c(.x, 1), end=c(.y, 4)))) %>% 
        as.tibble()
    

    这是ts.object 列的最后两行:

    df_ts$ts.object[[6]]
    #         Qtr1     Qtr2     Qtr3     Qtr4
    #2004 41.27360 26.65586 28.27986 35.19115
    #2005 41.72746 24.04185 32.32810 37.32871
    #2006 46.21315 29.34633 36.48291 42.97772
    #2007 48.90152 31.18022 37.71788 40.42021
    #2008 51.20686 31.88723 40.97826 43.77249
    
    df_ts$ts.object[[7]]
    #         Qtr1     Qtr2     Qtr3     Qtr4
    #2005 41.72746 24.04185 32.32810 37.32871
    #2006 46.21315 29.34633 36.48291 42.97772
    #2007 48.90152 31.18022 37.71788 40.42021
    #2008 51.20686 31.88723 40.97826 43.77249
    

    或者使用基础 R 中的Map

    df %>% mutate(ts.object = Map(function(x, y) window(austourists, start=c(x, 1), end=c(y, 4)), yr_start, yr_end))
    

    【讨论】:

    • 啊完美。我正在使用 map2 函数,但不知道如何嵌套它们。谢谢,这按预期工作!
    猜你喜欢
    • 2020-07-12
    • 2012-01-28
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2019-06-27
    • 2013-11-27
    • 2018-11-01
    • 2019-04-01
    相关资源
    最近更新 更多