【发布时间】:2021-11-21 13:55:54
【问题描述】:
我正在使用组合或 rmarkdown 和 gtsummary 来创建描述性表。将表格编成 html 时看起来很棒。
但是,当被编织成单词时,它们完全失去了格式。
由于我需要从这些表格中创建图表,因此我有兴趣将这些表格编入 word 或 excel。根据我的研究,似乎不可能将这些表格编成优秀。
所以我尝试用 Kable 包装打印语句,然后编织成单词。但是 kable 似乎只适用于数据帧,而 gtsummary::tbl_cross 创建的对象是它自己的类。
Error in as.data.frame.default(x) :
cannot coerce class 'c("tbl_cross", "tbl_summary", "gtsummary")' to a data.frame
Calls: <Anonymous> ... print -> kable -> as.data.frame -> as.data.frame.default
Execution halted
我的问题:
- 有没有办法将 kable 与 gtsummary 一起使用?
- 如果没有,为菜鸟创建可编辑表格(可以粘贴到 Excel 中制作图表的表格)的最佳方法是什么? 请注意,我只需要包含在决赛表中的百分比,而不是频率,但 gtsummary 没有仅保留百分比的选项。
- 是否有与我所缺少的完全不同的方法?
非常感谢您的建议,请参阅此处获取我的代码。
我的代码:
---
title: "Untitled"
author: "me"
date: "9/29/2021"
output:
html_document: default
word_document: default
---
```{r setup, include=FALSE}
# Remove items from memory and environment
rm(list = ls())
# load required libraries
library(magrittr)
library(dplyr)
library(gtsummary)
# File locations
# read in data
data_in <- readr::read_table2('Q17_1 Q17_2 Q17_3 Q17_4 survey
No Yes No Yes m1
No Yes No No m2
Yes Yes Yes Yes m1
No No Yes No m2
No No Yes Yes m1
Yes No Yes No m2
No No Yes Yes m1
No No Yes No m2
Yes No Yes Yes m1
')
vct <- data_in %>% select(matches("Q")) %>% names(.)
```
```{r , include=FALSE}
# set up user function create tables
run_xtab <- function(v1) {
out <- data_in%>%
tbl_cross(
row = !!rlang::sym(v1),
col = survey,
percent = 'column',
label = list(survey~v1),
missing_text = "no"
) %>%
add_p(source_note = TRUE) %>%
bold_labels()
return(out)
}
```
```{r loop_print, results = 'asis', warning=FALSE, message=FALSE,error=FALSE,echo=FALSE}
# loop through the questions to create the xtables
library(knitr)
for (i in vct) {
tbl <- run_xtab(i) # build gtsummary table
# print(kable(tbl)) # Kable does not like gtsummary object
# stargazer(tbl) # neither does star gazers
# tbl <-as.data.frame(tbl) # try converting table to df
print(tbl) # simple print works with html, but knitting to word loses formatting
}
```
【问题讨论】:
标签: r r-markdown kable gtsummary