FBurns FBurns - 1 month ago 5
R Question

Extract unique values from column in dataframe, grouped by ID

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

Answer
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
Comments