Relative frequencies / proportions with dplyr

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

    This answer is based upon Matifou's answer.

    First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

    Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

    getOption("scipen") 
    options("scipen"=10) 
    mtcars %>%
    count(am, gear) %>% 
    mutate(freq = (n / sum(n)) * 100)
    

提交回复
热议问题