带有R Markdown的交叉制表 [英] Cross Tabulation with R Markdown

查看:75
本文介绍了带有R Markdown的交叉制表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难为 PDF编织的R Markdown 文档创建简单美观的交叉表.我有一个与此示例相似的数据集:

I have struggle creating a simple nice looking cross tabulation for a PDF knitted R Markdown document. I have a data set that is similar to this example:

library(tidyverse)
fakeData <- tibble(id = c(1,2,3,4,5,6,7,8,9,10),
                   bmi = c("normal", "overweighted", "underweighted", "normal", "normal", "overweighted",
                           "normal", "overweighted", "underweighted","normal"),
                   gender = c("M", "F", "M", "M", "F", "F", "M", "F", "F", "F"))

我想得到这样的输出:

有没有人有技巧/已知好的软件包来做到这一点?非常感谢!

Have anyone a trick/ a known good package to do this? Thanks a lot!

推荐答案

我认为 janitor -程序包可以在这里为您提供帮助...

I think the janitor-package can help you out here...

请注意:总计"列中的百分比与您期望的输出不匹配...这是因为您在输出中混合了按百分比和按行百分比计算.这真的是您想要的吗?

note: the percentages in the 'total' column do not match your desired output... That is because you are mixing colwise and rowwise percentage calculation in your output.. Is that really what you want?

library( janitor )

fakeTable <- fakeData %>% 
  tabyl( gender, bmi ) %>% 
  adorn_totals( where = c("row", "col") ) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting() %>%
  adorn_ns( position = "front" ) %>%
  adorn_title("combined")

# gender/bmi    normal overweighted underweighted       Total
#          F 2 (33.3%)    3 (50.0%)     1 (16.7%)  6 (100.0%)
#          M 3 (75.0%)    0  (0.0%)     1 (25.0%)  4 (100.0%)
#      Total 5 (50.0%)    3 (30.0%)     2 (20.0%) 10 (100.0%)

针织

library(knitr)
library(kableExtra)
fakeTable %>%
  kable() %>%
  kable_styling(bootstrap_options = c("condensed", "striped", "bordered")) 

这篇关于带有R Markdown的交叉制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆