R中每周因子频率的总和

时间:2015-05-25 05:16:53

标签: 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的计数?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)