簡體   English   中英

與 R Markdown 的交叉表

[英]Cross Tabulation with R Markdown

我很難為PDF 針織 R Markdown文檔創建一個簡單漂亮的交叉表。 我有一個類似於此示例的數據集:

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"))

我想得到一個像這樣的 output :

期望的輸出

有沒有人有技巧/已知好的 package 來做到這一點? 非常感謝!

我認為janitor -package 可以在這里為您提供幫助...

注意:“總計”列中的百分比與您想要的 output 不匹配...那是因為您在 output 中混合了 colwise 和 rowwise 百分比計算。這真的是您想要的嗎?

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")) 

在此處輸入圖像描述

我認為 package summarytools可以產生所需的 output。 使用你的 fakeData:

library(summarytools)
print(ctable(x = fakeData$gender, y = fakeData$bmi, prop = "t"),
      method = "render")

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM