2016-05-20 61 views
0

我有不同人在不同日期的多個觀察,例如,dplyr總結日期到工作日

df <- data.frame(id= c(rep(1,5), rep(2,8), rep(3,7)), 
       dates = seq.Date(as.Date("2015-01-01"), by="month", length=20)) 

這裏我們有3個人(id),每個人的觀察量不同。

我現在要計算每個人的星期一,星期二等。

這應該使用dplyrsummarize完成,因爲我的真實數據集有更多的列,我用不同的統計數據進行總結。

它應該是一些像這樣:

summa <- df %>% group_by(id) %>% 
      summarize(mondays = #numberof mondays, 
        tuesdays = #number of tuesdays, 
         .........) 

如何才能實現這一目標?

回答

3

您可以使用lubridate包:

library(lubridate) 

summa <- df %>% group_by(id) %>% 
    summarize(mondays = sum(wday(dates) == 2), 
    .... 
3

我會做到以下幾點:

summa <- count(df, id, day = weekdays(dates)) 

# or: 
# summa <- df %>% 
#  mutate(day = weekdays(dates)) %>% 
#  count(id, day) 

head(summa) 
#Source: local data frame [6 x 3] 
#Groups: id [2] 
# 
#  id  day  n 
# (dbl)  (chr) (int) 
#1  1 Donnerstag  1 
#2  1 Freitag  1 
#3  1 Mittwoch  1 
#4  1 Sonntag  2 
#5  2 Dienstag  2 
#6  2 Donnerstag  1 

但你也可以重塑寬格式:

library(tidyr) 
spread(summa, day, n, fill=0) 
#Source: local data frame [3 x 8] 
#Groups: id [3] 
# 
#  id Dienstag Donnerstag Freitag Mittwoch Montag Samstag Sonntag 
# (dbl) (dbl)  (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) 
#1  1  0   1  1  1  0  0  2 
#2  2  2   1  1  1  1  1  1 
#3  3  1   0  2  1  2  0  1 

我的結果是德國人,但你的將是你自己的,當然語言。列名是德國工作日。


如果你想如上使用使用summarize明確地就可以實現相同的:

summa <- df %>% 
    group_by(id, day = weekdays(dates)) %>% 
    summarize(n = n()) # or do something with summarise_each() for many columns 
1

基準日期功能:

summa <- df %>% group_by(id) %>% 
    summarise(monday = sum(weekdays(dates) == "Monday"), 
       tuesday = sum(weekdays(dates) == "Tuesday"))