Search code examples
r

Long format data structure, counting number of occurrences by a categorical variable


I have a long formatted data structure of repeated measures. Below is a simplified example.

df <- data.frame(ID =c("AA1", "AA2", "AA3", "AA4", "AA1", "AA2", "AA3", "AA4"),
                 Event = c(1, 1, 0, 1, 0, 0, 0, 1))

I want to count the total number of times an "ID" has an "Event".

Since AA3 had 0 for both events, AA1 and AA2 had 1 event, and AA4 had both events I would like to produce a table that looks like this:

Event 0 1 2
1 2 1

I've seen other questions but they were with frequency tables. I'm not interested in seeing "ID" in this table, just a one row table that has the total number of individuals who had 0, 1, or 2 'events'.


Solution

  • Using table:

    table(table(df)[, 1])
    # 0 1 2 
    # 1 2 1