Creating a table for frequency analysis results in R

前端 未结 3 803
执笔经年
执笔经年 2020-12-21 19:21

I need to create a table of a certain type and based on a certain template.

This is my data:

df = structure(list(group = c(1L, 1L, 2L, 2L, 2L, 3L, 3L,          


        
3条回答
  •  既然无缘
    2020-12-21 19:50

    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`
    #                           
    #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%)
    

提交回复
热议问题