计数和百分比的二乘二表

计数和百分比的二乘二表

本文介绍了R中的计数和百分比的二乘二表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是这样的:

   OnAntibiotic Gender
1          Yes    Male
2          Yes    Male
3          Yes  Female
4          Yes  Female
5          Yes  Female
6          Yes  Female
7          Yes  Female
8          Yes  Female
9          Yes  Female
10         Yes  Female
11         Yes    Male
12         Yes    Male
13         Yes    Male
14         Yes    Male
15           No Female
16           No Female
17           No Female
18           No   Male
19           No   Male

我想要创建一个具有计数和百分比的二乘二表。如下所示:

I would like to create a two by two table with count and percentage. Something like below:

       Yes (%)      No (%)   
Male    6 (42.8%)   2 (40%) 
Female  8 (57.1%)   3 (60%)

我的代码是:

library(dplyr)
df %>% 
  group_by(Gender, OnAntibiotic) %>% 
  summarise(count=n())%>% 
  mutate(freq= n/sum(n))

请帮助我。

推荐答案

library(dplyr)
df %>% group_by(Gender,OnAntibiotic) %>% mutate(n=n()) %>% 
        group_by(OnAntibiotic) %>% distinct(OnAntibiotic,Gender,n)%>%
        mutate(Per=n/sum(n), np=paste0(n," (",round(Per*100,2)," %)")) %>%
        select(-n,-Per) %>% spread(OnAntibiotic,np)

# A tibble: 2 x 3
  Gender No       Yes        
  <fct>  <chr>    <chr>      
1 Female 3 (60 %) 8 (57.14 %)
2 Male   2 (40 %) 6 (42.86 %)

这篇关于R中的计数和百分比的二乘二表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 01:10