首页 > 解决方案 > 将 R markdown 中的 3 向列联表打印到 docx

问题描述

我正在尝试使用 R markdown 创建一个包含三向列联表的报告。我可以使用 ftable() 很容易地创建表格,但它们的格式不适合在 markdown 中打印。

输出必须是 DOCX 文档。因此,任何设计为 HTML 或 LaTeX 格式的东西对我都没有用。

knitr 中的 kable() 函数不适用于 ftables,许多其他选项只会将其打印为数据框。将 ftable 转换为数据框时,它会弄乱它的布局方式,因此这些也无济于事。

我创建了一个使用 ftable 创建的 3 路表的可重现示例,该示例应该与我需要输出的表的大小大致相同:

library(tidyverse)
# this data set is included in dplyr
data("starwars")
data=starwars
#the next couple of lines are just me trimming down the information to be used in the table
data=data %>% filter(species=="Human" | species=="Droid" | species=="Zabrak" | species=="Mirialan" | species=="Wookiee")
tabledata=data[,c(8:10)]
#here's the actual table
table1 = ftable(tabledata,col.vars=c(3,1))
table1

如果可能的话,我希望有一个相当简单的解决方案(也许是一个为我做的包,或其他东西)。该报告将包含许多表格,因此做一些过于复杂的事情会花费很长时间(另外,我最近才开始使用 R)。

提前感谢大家可以提供的任何帮助!

标签: rmarkdownr-markdown

解决方案


您是否愿意接受稍有不同的 ftable 表示?例如,这里有一个使用 flextable 的解决方案。这在 Word 中呈现得非常好……去年我使用 flextable 在一个 500 页的文档中构建表格。

library(flextable)
library(dplyr)
library(magrittr)

table1 = ftable(tabledata,col.vars=c(3,1))

data.frame(table1) %>% spread(species, Freq) %>% 
     regulartable %>% merge_v(j = ~homeworld) %>% autofit()

在此处输入图像描述


推荐阅读