r - 将 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)。
提前感谢大家可以提供的任何帮助!
解决方案
您是否愿意接受稍有不同的 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()
推荐阅读
- oracle - Oracle Apex 交互式网格未保存更新的值
- internet-explorer-8 - 无法从 Internet Explorer-8 更新我的浏览器
- javascript - 如何在不使用 iframe、嵌入和对象标签的情况下在网页中打开另一个网页
- python - 将函数应用于数据框中的列表并创建一个包含结果的新列
- vbscript - VB脚本查找它是在32位还是64位运行
- javascript - 使用 Laravel Mix 加载后页面上未检测到 Alpine.js
- python - 如何使用python将soap响应中具有多个命名空间的嵌套xml文件转换为数据框
- javascript - 使用javascript从json文件中获取数据并显示数据表
- rest - 多语言支持应该由前端还是后端处理?
- python - 为什么我会收到此错误以及如何解决?