Extend contigency table with proportions (percentages)

后端 未结 6 1212
悲哀的现实
悲哀的现实 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 02:53

    Here is another example using the lapply and table functions in base R.

    freqList = lapply(select_if(tips, is.factor), 
                  function(x) {
                      df = data.frame(table(x))
    
                      df = data.frame(fct = df[, 1], 
                                      n = sapply(df[, 2], function(y) {
                                          round(y / nrow(dat), 2)
                                        }
                                    )
                                )
                      return(df) 
                        }
                    )
    

    Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

提交回复
热议问题