[英]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))
我有FPP數據包中的澳大利亞游客數據。 我想創建多個時間序列對象,這些對象將根據不同的開始年份進行修剪。
df <- as.data.frame(1999:2005)
colnames(df) <- "yr_start"
df$yr_end <- 2008
我想重復上述的window函數,但要在df
使用給定的輸入。 我試圖使用map
和nest
創建時間序列對象並將其嵌套到位。
我的目標是具有以下結構的數據框
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函數運行指數平滑模型。
您可以在yr_start
和yr_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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.