首页 > 解决方案 > 在 rmarkdown 中创建可编辑的表

问题描述

我正在使用组合或 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

我的问题:

  1. 有没有办法将 kable 与 gtsummary 一起使用?
  2. 如果没有,为菜鸟创建可编辑表格(可以粘贴到 Excel 中制作图表的表格)的最佳方法是什么。请注意,我只需要包含在决赛表中的百分比,而不是频率,但 gtsummary 没有仅保留百分比的选项。
  3. 有没有完全不同于我所缺少的方法?

非常感谢您的建议,请参阅此处获取我的代码。

我的代码:

---
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 
}
```

标签: rr-markdownkablegtsummary

解决方案


我认为您最好的资源将是 R markdown 上的 gtsummary 小插图。http://www.danieldsjoberg.com/gtsummary/articles/rmarkdown.html 在小插图中,您会发现此表概述了如何将 gtsummary 表导出到各种 R markdown 输出类型。 在此处输入图像描述

在您的情况下,我建议您使用该as_flex_table()函数将 gtsummary 表转换为 flextable。

例如,您可以更新您的函数以包含此转换。(小插图中概述的更多信息/选项。)

```{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() %>%
    as_flex_table()
  
  return(out)
}
```

推荐阅读