Relative frequencies / proportions with dplyr

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

    Despite the many answers, one more approach which uses prop.table in combination with dplyr or data.table.

    library("dplyr")
    mtcars %>%
        group_by(am, gear) %>%
        summarise(n = n()) %>%
        mutate(freq = prop.table(n))
    
    library("data.table")
    cars_dt <- as.data.table(mtcars)
    cars_dt[, .(n = .N), keyby = .(am, gear)][, freq := prop.table(n) , by = "am"]
    

提交回复
热议问题