Creating a table for frequency analysis results in R

…衆ロ難τιáo~ 提交于 2019-11-29 17:12:28

I have to admit that I'm not clear on what you're trying to do. Unfortunately your expected output image does not help.

I assume you are asking how to calculate a 2-way contingency table and show both counts and percentages (of total). Here is a tidyverse possibility

library(tidyverse)
df %>%
    group_by(group, degree) %>%
    summarise(n = n(), perc = n() / nrow(.)) %>%
    mutate(entry = sprintf("%i (%3.2f%%)", n, perc * 100)) %>%
    select(-n, -perc) %>%
    spread(group, entry, fill = "0 (0.0%%)")
## A tibble: 3 x 4
#  degree            `1`        `2`        `3`
#  <fct>             <chr>      <chr>      <chr>
#1 Mild severity     3 (30.00%) 3 (30.00%) 2 (20.00%)
#2 Moderate severity 0 (0.0%%)  0 (0.0%%)  1 (10.00%)
#3 Severe severity   0 (0.0%%)  0 (0.0%%)  1 (10.00%)

you want the fractions, together with the total numbers? Try:

n=table(df$degree,df$group)
df=as.data.frame(cbind(n/colSums(n)*100,n))

using base R:

a = transform(data.frame(table(df)),Freq = sprintf("%d (%3.2f%%)",Freq,prop.table(Freq)*100))
data.frame(t(unstack(a,Freq~degree)))
                          X1         X2         X3
Mild.severity     3 (30.00%) 3 (30.00%) 2 (20.00%)
Moderate.severity  0 (0.00%)  0 (0.00%) 1 (10.00%)
Severe.severity    0 (0.00%)  0 (0.00%) 1 (10.00%)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!