I have a dataframe data0 with id's and dates like this:
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
Reproduce:
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")
How can I summarize dates by id so that I come out with a structure with counts like this? :
id 2016-10-19 2016-10-20 2016-10-21 2016-10-22
1 1 2
2 1 1
3 2 1
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")
Use the built in table function.
> 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
Another way around using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.