Extend contigency table with proportions (percentages)

后端 未结 6 1213
悲哀的现实
悲哀的现实 2020-11-29 02:39

I have a contingency table of counts, and I want to extend it with corresponding proportions of each group.

Some sample data (tips data set from gg

6条回答
  •  忘掉有多难
    2020-11-29 03:05

    Here's a tidyverse version:

    library(tidyverse)
    data(diamonds)
    
    (as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))
    

    Or if you want a handy function:

    getPercentages <- function(df, colName) {
      df.cnt <- df %>% select({{colName}}) %>% 
        table() %>%
        as.data.frame() %>% 
        rename({{colName}} :=1, Freq=2) %>% 
        mutate(Perc=100*Freq/sum(Freq))
    }
    

    Now you can do:

    diamonds %>% getPercentages(cut)
    

    or this:

    df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
    ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)
    

提交回复
热议问题