2017-11-02 5 views
0
library(fpp) 
library(purrr) 
library(tidyr) 

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

FPP 패키지의 호주 관광객 데이터가 있습니다. 서로 다른 시작 연도를 기준으로 트리밍 된 여러 개의 시계열 객체를 만들고 싶습니다. 위와 같지만 df에서 주어진 입력을 볼 때DataFrame에 시계열 객체 Nested

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

나는 윈도우 함수를 반복하고 싶습니다. 나는 mapnest을 사용하여 timeseries 오브젝트를 생성하고 그것을 네스트로 위치 시키려고했다.

내가

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> 

목표의 구조와 dataframe을 목표로하고있어 이러한 TS 개체에 대한지도 기능을 사용하여 지수 평활 모델을 실행하는 데 나중에이 TS 오브젝트를 사용하는 것입니다.

답변

2

당신은 map2yr_start 이상과 yr_end 열을 사용하고 start-end년의 각 쌍에 대한 ts 객체를 생성 할 수 있습니다 : 여기

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

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> 

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)) 
+1

Ah로 사용하십시오. map2 함수로 놀고 있었지만 중첩하는 방법을 잘 모르겠습니다. 감사합니다. 예상대로 작동합니다! – msubbaiah