简体   繁体   English

将时间序列对象嵌套到DataFrame中

[英]Nest Time-Series object into a DataFrame

library(fpp)
library(purrr)
library(tidyr)

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

I have the Australian tourists data from the FPP package. 我有FPP数据包中的澳大利亚游客数据。 I'd like to create multiple time series objects that are trimmed based on different starting years. 我想创建多个时间序列对象,这些对象将根据不同的开始年份进行修剪。

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

I'd like to repeat the window function as seen above but with the given inputs in df . 我想重复上述的window函数,但要在df使用给定的输入。 I was trying to use map and nest to create a timeseries object and the nest it into place. 我试图使用mapnest创建时间序列对象并将其嵌套到位。

I'm aiming for a dataframe with the structure of 我的目标是具有以下结构的数据框

   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>

The goal is to use these ts objects later to run Exponential Smoothing models using the map function on these ts objects. 目标是稍后使用这些ts对象在这些ts对象上使用map函数运行指数平滑模型。

You can use map2 over yr_start and yr_end columns and construct a ts object for each pair of start-end years: 您可以在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()

Here are the last two rows in ts.object column: 这是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

Or use Map from base R: 或使用基于R的Map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM