Relative frequencies / proportions with dplyr

前端 未结 9 2386
灰色年华
灰色年华 2020-11-22 09:25

Suppose I want to calculate the proportion of different values within each group. For example, using the mtcars data, how do I calculate the relative f

9条回答
  •  一个人的身影
    2020-11-22 09:29

    I wrote a small function for this repeating task:

    count_pct <- function(df) {
      return(
        df %>%
          tally %>% 
          mutate(n_pct = 100*n/sum(n))
      )
    }
    

    I can then use it like:

    mtcars %>% 
      group_by(cyl) %>% 
      count_pct
    

    It returns:

    # A tibble: 3 x 3
        cyl     n n_pct
        
    1     4    11  34.4
    2     6     7  21.9
    3     8    14  43.8
    

提交回复
热议问题