2015-05-25 31 views
0

假設我有以下數據的總和:R中由周因子頻率

set.seed(123) 
timeseq <- as.Date(Sys.time() + cumsum(runif(1000)*86400)) 
data <- sample(c("A","B","C"), 1000,replace = TRUE) 
data.frame(timeseq,data) 

有誰知道如何按周發現A,B,C的計數?

回答

0

您可以使用lubridate來解決這個問題。所以,使用它與dplyr

library(lubridate) 

data.frame(timeseq,data) %>% 
    mutate(week=floor_date(timeseq, "week")) %>% 
    group_by(data, week) %>% 
    tally 

其中有這樣的輸出:

Source: local data frame [216 x 3] 
Groups: data 

    data  week n 
1  A 2015-05-24 4 
2  A 2015-05-31 3 
3  A 2015-06-07 3 
4  A 2015-06-14 5 
5  A 2015-06-21 6 
6  A 2015-06-28 3 
7  A 2015-07-05 8 
8  A 2015-07-12 3 
9  A 2015-07-19 4 
10 A 2015-07-26 6 
0

如果你想按週數回答那就試試這個

set.seed(123) 
timeseq <- as.Date(Sys.time() + cumsum(runif(1000)*86400)) 
data <- sample(c("A","B","C"), 1000,replace = TRUE) 
data.frame(timeseq,data) 

mydf <- as.Date(timeseq, format="%d-%m-%Y") 
weeknum <- as.numeric(format(mydf+3, "%U")) 
weeknum 

new_data <- data.frame(timeseq,weeknum,data) 

table(new_data$weeknum,new_data$data)