Search code examples
rfrequency

R: frequency with group by ID


I have a data frame like this:

ID Cont
1   a
1   a
1   b
2   a
2   c
2   d

I need to report the frequence of "Cont" by ID. The output should be

ID Cont Freq
1   a    2
1   b    1
2   a    1
2   c    1
2   d    1

Solution

  • Using dplyr, you can group_by both ID and Cont and summarise using n() to get Freq:

    library(dplyr)
    res <- df %>% group_by(ID,Cont) %>% summarise(Freq=n())
    ##Source: local data frame [5 x 3]
    ##Groups: ID [?]
    ##
    ##     ID   Cont  Freq
    ##  <int> <fctr> <int>
    ##1     1      a     2
    ##2     1      b     1
    ##3     2      a     1
    ##4     2      c     1
    ##5     2      d     1
    

    Data:

    df <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L), Cont = structure(c(1L, 
    1L, 2L, 1L, 3L, 4L), .Label = c("a", "b", "c", "d"), class = "factor")), .Names = c("ID", 
    "Cont"), class = "data.frame", row.names = c(NA, -6L))
    ##  ID Cont
    ##1  1    a
    ##2  1    a
    ##3  1    b
    ##4  2    a
    ##5  2    c
    ##6  2    d