Relative frequencies / proportions with dplyr

前端 未结 9 2429
灰色年华
灰色年华 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:34

    Here is a general function implementing Henrik's solution on dplyr 0.7.1.

    freq_table <- function(x, 
                           group_var, 
                           prop_var) {
      group_var <- enquo(group_var)
      prop_var  <- enquo(prop_var)
      x %>% 
        group_by(!!group_var, !!prop_var) %>% 
        summarise(n = n()) %>% 
        mutate(freq = n /sum(n)) %>% 
        ungroup
    }
    

提交回复
热议问题