2016-03-16 63 views
1

我是新來的R和我無法理解如何聚合的每週數據我有年度數據?每週數據轉換爲年度數據

  Week obs 
1 2004-01-04 23 
2 2004-01-11 36 
3 2004-01-18 18 
4 2004-01-25 26 
5 2004-02-01 17 
6 2004-02-08 17 
7 2004-02-15 26 
8 2004-02-22 21 
9 2004-02-29 34 
10 2004-03-07 21 
11 2004-03-14 30 
12 2004-03-21 31 
13 2004-03-28 31 
14 2004-04-04 38 
15 2004-04-11 14 
16 2004-04-18 16 
17 2004-04-25 44 
18 2004-05-02 17 
19 2004-05-09 43 
20 2004-05-16 31 
21 2004-05-23 31 
22 2004-05-30 33 
23 2004-06-06 13 
24 2004-06-13 13 
25 2004-06-20 46 
26 2004-06-27 34 
27 2004-07-04 27 
28 2004-07-11 24 
29 2004-07-18 20 
30 2004-07-25 29 
31 2004-08-01 29 
32 2004-08-08 12 
33 2004-08-15 16 
34 2004-08-22 26 
35 2004-08-29 29 
36 2004-09-05 27 
37 2004-09-12 8 
38 2004-09-19 18 
39 2004-09-26 14 
40 2004-10-03 25 
41 2004-10-10 26 
42 2004-10-17 11 
43 2004-10-24 24 
44 2004-10-31 17 
45 2004-11-07 11 
46 2004-11-14 19 
47 2004-11-21 8 
48 2004-11-28 16 
49 2004-12-05 19 
50 2004-12-12 14 
51 2004-12-19 13 
52 2004-12-26 29 

我只想留住

2004 1215 

回答

1

使用data.table,給予df$WeekDate類:

library(data.table) 
setDT(df)[,.(abs = sum(obs)), by = year(df$Week)] 
# year abs 
#1: 2004 1215 
1

在基礎R,

aggregate(df$obs, list(year = format(df$Week, '%Y')), sum) 

#  year x 
# 1 2004 1215 

或具有lubridate

library(lubridate) 
aggregate(df$obs, list(year = year(df$Week)), sum) 

#  year x 
# 1 2004 1215 

lubridatedplyr

library(dplyr) 
df %>% group_by(year = year(Week)) %>% summarise(obs = sum(obs)) 

# Source: local data frame [1 x 2] 
# 
# year obs 
# (dbl) (int) 
# 1 2004 1215 
相關問題