I am trying to export R output table to word file. I am using ReporteRs
package to do this. I capture the output and pass it to a paragraph. In this approach, the tidy output gets distorted and doesn't look nice as it was in console or when saved to a text file. How do I pass the output as is to word file? Thank you in advance.
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")
You have to use a monospace font (as R console output is using monospace font)
library(gmodels)
data(infert, package = "datasets")
xx=capture.output(CrossTable(infert$education, infert$induced, expected = TRUE, format="SPSS"))
Solution 1: use an existing style (from your template) that is using a monospaced font, i.e rRawOutput
in the default template
library( ReporteRs )
mydoc <- docx(title = "Summary")
mydoc <- addParagraph( mydoc, xx, stylename = "rRawOutput" )
writeDoc( mydoc, file = "Summary.docx")
Solution 2: use pot
function to create a piece of text with a specified monospace font
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")
Solution 3: this one does not really answer your question as it does not use gmodels but I like the output:
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")