从一些虚拟数据开始:
c_data <- data.frame(Team=paste("team", sample(1:3,10, replace=TRUE)),
Date_received=paste(sample(1:31,10,replace=TRUE), sample(1:12,10,replace=TRUE), rep(10,10,replace=TRUE), sep="/"))
c_data
Team Date_received
1 team 3 13/7/10
2 team 1 2/5/10
3 team 2 14/5/10
4 team 1 15/4/10
5 team 1 25/1/10
6 team 3 30/4/10
7 team 3 23/9/10
8 team 3 7/9/10
9 team 2 7/6/10
10 team 2 4/6/10
首先,您必须将日期声明为 Date 对象。
c_data$Date_received <- as.Date(c_data$Date_received, "%d/%m/%y")
要提取月份,没有比这更简单的了:
c_data$month <- format(c_data$Date_received, "%m")
c_data$month
[1] "07" "05" "05" "04" "01" "04" "09" "09" "06" "06"
然后,要找到每个团队每月的发病率,您只需根据您的团队和月份制作表格:
t_data <- table(c_data$Team, c_data$month)
t_data
01 04 05 06 07 09
team 1 1 1 1 0 0 0
team 2 0 0 1 2 0 0
team 3 0 1 0 0 1 2
现在作为 data.frame (用于绘图目的):
d_data <- as.data.frame(t_data)
d_data
Var1 Var2 Freq
1 team 1 01 1
2 team 2 01 0
3 team 3 01 0
4 team 1 04 1
5 team 2 04 0
6 team 3 04 1
7 team 1 05 1
8 team 2 05 1
9 team 3 05 0
10 team 1 06 0
11 team 2 06 2
12 team 3 06 0
13 team 1 07 0
14 team 2 07 0
15 team 3 07 1
16 team 1 09 0
17 team 2 09 0
18 team 3 09 2
# Back to Date objects
d_data$Var2 <- as.Date(paste("1",d_data$Var2,"10",sep="/"), "%d/%m/%y")
library(ggplot2)
ggplot(d_data, aes(Var2, Freq, group = Var1, color = Var1)) +
geom_line()