Extend contigency table with proportions (percentages)

后端 未结 6 1205
悲哀的现实
悲哀的现实 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:03

    If it's conciseness you're after, you might like:

    prop.table(table(tips$smoker))
    

    and then scale by 100 and round if you like. Or more like your exact output:

    tbl <- table(tips$smoker)
    cbind(tbl,prop.table(tbl))
    

    If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:

    tblFun <- function(x){
        tbl <- table(x)
        res <- cbind(tbl,round(prop.table(tbl)*100,2))
        colnames(res) <- c('Count','Percentage')
        res
    }
    
    do.call(rbind,lapply(tips[3:6],tblFun))
           Count Percentage
    Female    87      35.66
    Male     157      64.34
    No       151      61.89
    Yes       93      38.11
    Fri       19       7.79
    Sat       87      35.66
    Sun       76      31.15
    Thur      62      25.41
    Dinner   176      72.13
    Lunch     68      27.87
    

    If you don't like stack the different tables on top of each other, you can ditch the do.call and leave them in a list.

提交回复
热议问题