Count occurrences of factor in R, with zero counts reported

前端 未结 5 1591
死守一世寂寞
死守一世寂寞 2021-02-07 23:58

I want to count the number of occurrences of a factor in a data frame. For example, to count the number of events of a given type in the code below:

library(plyr         


        
相关标签:
5条回答
  • 2021-02-08 00:38

    In data you put your dataframe and into levels your categories.

    table(factor(data, levels = 1:5)) 
    
    0 讨论(0)
  • 2021-02-08 00:40

    Using dplyr library

    library(dplyr)
    data <- data.frame(level = c('A', 'A', 'B', 'B', 'B', 'C'),
                       value = c(1:6))
    
    data %>%
      group_by(level) %>%
      summarize(count = n()) %>%
      View
    

    If you choose also to perform mean, min, max operations, try this

    data %>%
      group_by(level) %>%
      summarise(count = n(), Max_val = max(value), Min_val = min(value)) %>%
      View
    
    0 讨论(0)
  • 2021-02-08 00:49

    Quite similar to @DWin's answer:

    > aggregate(quantity~type, events, FUN=sum)
      type quantity
    1    A        3
    2    B        1
    3    C        0
    
    0 讨论(0)
  • 2021-02-08 00:58

    You get this for free if you define your events variable correctly as a factor with the desired three levels:

    R> events <- data.frame(type = factor(c('A', 'A', 'B'), c('A','B','C')), 
    +                       quantity = c(1, 2, 1))
    R> events
      type quantity
    1    A        1
    2    A        2
    3    B        1
    R> table(events$type)
    
    A B C 
    2 1 0 
    R> 
    

    Simply calling table() on the factor already does the right thing, and ddply() can too if you tell it not to drop:

    R> ddply(events, .(type), summarise, quantity = sum(quantity), .drop=FALSE)
      type quantity
    1    A        3
    2    B        1
    3    C        0
    R> 
    
    0 讨论(0)
  • 2021-02-08 00:59
    > xtabs(quantity~type, events)
    type
    A B C 
    3 1 0 
    
    0 讨论(0)
提交回复
热议问题