您必须使用等宽字体(因为 R 控制台输出使用等宽字体)
library(gmodels)
data(infert, package = "datasets")
xx=capture.output(CrossTable(infert$education, infert$induced, expected = TRUE, format="SPSS"))
解决方案 1:使用使用等宽字体的现有样式(来自您的模板),即rRawOutput
在默认模板中
library( ReporteRs )
mydoc <- docx(title = "Summary")
mydoc <- addParagraph( mydoc, xx, stylename = "rRawOutput" )
writeDoc( mydoc, file = "Summary.docx")
解决方案2:使用pot
函数创建一段具有指定等宽字体的文本
library( ReporteRs )
mydoc <- docx(title = "Summary")
mypot <- pot( paste(xx, collapse = "\n"),
format = textProperties(font.family = "Courier New", font.size = 9) )
mydoc <- addParagraph( mydoc, mypot, par.properties = parLeft() )
writeDoc( mydoc, file = "Summary.docx")
解决方案 3:这个并没有真正回答你的问题,因为它不使用 gmodels 但我喜欢输出:
library( ReporteRs )
library( rtable )
library( broom )
data(infert, package = "datasets")
myft = freqtable(table(infert$education, infert$induced))
ct = chisq.test(infert$education, infert$induced)
mydoc = docx(title = "Summary")
mydoc = addTitle(mydoc, "Table", level = 2)
mydoc = addFlexTable( mydoc, myft )
mydoc = addTitle(mydoc, "Chi-squared Test", level = 2)
mydoc = addFlexTable( mydoc, vanilla.table( tidy(ct) ) )
writeDoc( mydoc, file = "Summary.docx")