我有一个id为id的数据帧data0,日期如下:
id date
1 2016-10-20
1 2016-10-19
1 2016-10-20
2 2016-10-21
2 2016-10-22
3 2016-10-21
3 2016-10-21
3 2016-10-22
转载:
data0 <- structure(list(id = c(1, 1, 1, 2, 2, 3, 3, 3), date = structure(c(17094, 17093, 17094, 17095, 17096, 17095, 17095, 17096), class = "Date")), .Names = c("id", "date"), row.names = c(NA, -8L), class = "data.frame")
如何通过id汇总日期,以便我得出一个像这样的计数结构? :
id 2016-10-19 2016-10-20 2016-10-21 2016-10-22
1 1 2
2 1 1
3 2 1
答案 0 :(得分:3)
data0 <- structure(list(id = c(1, 1, 1, 2, 2, 3, 3, 3),
date = structure(c(17094, 17093, 17094, 17095, 17096, 17095, 17095, 17096), class = "Date")),
.Names = c("id", "date"), row.names = c(NA, -8L), class = "data.frame")
使用内置表函数。
> table(data0)
date
id 2016-10-19 2016-10-20 2016-10-21 2016-10-22
1 1 2 0 0
2 0 0 1 1
3 0 0 2 1
答案 1 :(得分:2)
使用xtabs
的另一种方式:
data0$col <- 1
xtabs(col~id+date, data0)
# date
#id 2016-10-19 2016-10-20 2016-10-21 2016-10-22
# 1 1 2 0 0
# 2 0 0 1 1
# 3 0 0 2 1