Relative frequencies / proportions with dplyr

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

    Here is a base R answer using aggregate and ave :

    df1 <- with(mtcars, aggregate(list(n = mpg), list(am = am, gear = gear), length))
    df1$prop <- with(df1, n/ave(n, am, FUN = sum))
    #Also with prop.table
    #df1$prop <- with(df1, ave(n, am, FUN = prop.table))
    df1
    
    #  am gear  n      prop
    #1  0    3 15 0.7894737
    #2  0    4  4 0.2105263
    #3  1    4  8 0.6153846
    #4  1    5  5 0.3846154 
    

    We can also use prop.table but the output displays differently.

    prop.table(table(mtcars$am, mtcars$gear), 1)
       
    #            3         4         5
    #  0 0.7894737 0.2105263 0.0000000
    #  1 0.0000000 0.6153846 0.3846154
    

提交回复
热议问题