Count occurrences of factor in R, with zero counts reported

前端 未结 5 1590
死守一世寂寞
死守一世寂寞 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: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
    

提交回复
热议问题