在控制台中捕获输出(漂亮且整洁)并将其写入 word 文件

Capture output in console (nice & tidy) and write it to word file

我正在尝试将 R 输出 table 导出到 word 文件。我正在使用 ReporteRs 包来执行此操作。我捕获输出并将其传递给一个段落。在这种方法中,整洁的输出会失真,并且看起来不像在控制台中或保存到文本文件时那样好看。如何将输出原样传递到 word 文件?先感谢您。

    data("cars2")
    mydoc = docx(title = "Summary")
    library(gmodels)
    aal<-capture.output(CrossTable(cars2$Country, cars2$Type, digits=2, chisq=T))
    #capture.output(CrossTable(cars2$Country, cars2$Type, digits=2, chisq=T, format="SPSS"), file="tests.txt")
    mydoc<-addParagraph( mydoc, aal)
    writeDoc( mydoc, file = "Summary.docx")

您必须使用等宽字体(因为 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")

方案二:使用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")