2016-12-20 38 views
2

我有一個有3列(月,年,值)的數據框df。使用n年的時間序列計算每月數據的季節均值

>head(df) 
     months year value 
     January 01 23875.00 
    February 01 15343.25 
     March 01 9584.25 
     April 01 19026.33 
      May 01 26324.00 
     June 01 31228.00 

每12行(從第一個一月起),今年進入02,03,04,等等。直到16 我需要計算季節性的手段,即 對於夏季(十二月,一月的平均,二月); (3月,4月,5月)的秋季平均值,(6月,7月,8月)的冬季平均值和(9月,10月,11月)的春季平均值。

然後創建一個新的數據框,其中包含季節,年份以及它們的平均值以獲取類似的內容。

>head(seasdf) 
season year value 
DJF 01  
MAM 01  
JJA 01  
SON 01  
DJF 02  
MAM 02  

與所有的年,直到16我搜索了用這種數據幀的類似的問題,但我無法找到一個方法來做到這一點。

對不起,這個菜鳥問題。

回答

2

我們假設同季相鄰個月都應該有相同的季度名稱和年份和季度是一年來命名,其中本季度結束。例如,2001年12月,2002年1月和2002年2月將全部成爲DJF 2002季度的一部分。

首先將年份和月份轉換爲"yearmon"類變量ym,然後添加1/12以推送月份。這是基於這樣一個事實,即yearmon變量存儲爲1月份的年份+0,2月份的1/12,2月份的2/12等等,然後將其轉換爲"yearqtr"類別變量yq。現在聚合valueyq注意到yearqtr變量排序正確,所以2001年第一季度將在2001年第二季度之前,等等。最後用問題中顯示的列重新構建聚合數據框。

library(zoo) # yearmon and yearqtr classes 

ym <- as.yearmon(paste(DF$months, DF$year), "%B %y") 
yq <- as.yearqtr(ym + 1/12) 

Ag <- aggregate(value ~ yq, DF, mean) 

season.name <- c("DJF", "MAM", "JJA", "SON") 
with(Ag, data.frame(year = as.integer(yq), season = season.name[cycle(yq)], value)) 

,並提供:

year season value 
1 2001 DJF 19609.12 
2 2001 MAM 18311.53 
3 2001 JJA 31228.00 

如果問題出確切的佈局並不重要,那麼我們就可以省略代碼的最後兩行以上,只是使用Ag

> Ag 
     yq value 
1 2001 Q1 19609.12 
2 2001 Q2 18311.53 
3 2001 Q3 31228.00 

注:以可重現形式輸入DF假定爲:

DF <- structure(list(months = c("January", "February", "March", "April", 
"May", "June"), year = c("01", "01", "01", "01", "01", "01"), 
    value = c(23875, 15343.25, 9584.25, 19026.33, 26324, 31228 
    )), .Names = c("months", "year", "value"), class = "data.frame", row.names = c(NA, -6L)) 
2

好像你months變量是標準的月份名稱,你可以匹配它在R上的month.name變量獲得一個月爲一個數字,即(一月將年1月將2等),並採取模數師3,從year取得賽季爲另一組變量一邊,那麼它應該在今年,旺季是微不足道的組,取平均值:

library(dplyr) 
df %>% group_by(season = match(months, month.name) %% 12 %/% 3, year) %>% 
     summarise(value = mean(value)) %>% ungroup() %>% 

     # optional: convert the season from number to meaningful labels which could also be 
     # summer, autumn, winter and spring 
     mutate(season = factor(season, levels = c(0,1,2,3), 
             labels = c("DJF", "MAM", "JJA", "SON"))) 

# A tibble: 3 × 3 
# season year value 
# <fctr> <int> <dbl> 
#1 DJF  1 19609.12 
#2 MAM  1 18311.53 
#3 JJA  1 31228.00 

如果十二月需要被軋到下一一年夏天,你可以加一個到year變量當months == "December"

df %>% group_by(season = match(months, month.name) %% 12 %/% 3, year = ifelse(months == "December", year + 1, year)) %>% 
     summarise(value = mean(value)) %>% ungroup() %>% 

     # optional: convert the season from number to meaningful labels which could also be 
     # summer, autumn, winter and spring 
     mutate(season = factor(season, levels = c(0,1,2,3), 
           labels = c("DJF", "MAM", "JJA", "SON"))) 
相關問題