Tito Sanz
Tito Sanz

Reputation: 1362

Reporting regression tables using rmarkdown in Word format

Trying to report regression tables in Word format using rmarkdown seems impossible. After trying hours and several options like here no one worked in my case. I want to report lm models using markdown and render to a .doc file.

Method 1:

Using memisc package to create a mtable object and render using pander:

> lm0 <- lm(hp ~ wt, mtcars)
> lm1 <- lm(qsec ~ hp, mtcars)
> lm2 <- lm(qsec ~ wt, mtcars)
> 
> library(memisc)
> 
> mt <- mtable(lm0, lm1, lm2)
> 
> pander::pander(mt)
Error in x[[i]] : subíndice fuera de  los límites
Además: Warning message:
In pander.default(mt) :
  No pander.method for "memisc_mtable", reverting to default.

Method 2:

Create a html object and include using includeHTML. So far this is the closed method to my desire output. However the table only contains one column like this:

```{r}
stargazer::stargazer(lm0, lm1, lm2, type = "html", title = "Results", out = "./pp.html")
shiny::includeHTML("pp.html")
```

Code above produces this in a word document: enter image description here

Method 3:

Using xtable also produces the same output above.

Any suggestions?

Upvotes: 7

Views: 4623

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269431

Use write_html (from the memisc package):

write_html(mt, "mt.html")

Now open the mt.html file in Word. This is what it looks like in Word. (continued after screenshot)

screenshot

Alternately use this to convert filePathIn (which is the path to the html file created) to filePathOut (which is the path to the docx file to be created from it). This works on Windows and even in cases where pandoc does not as it uses Word itself to do the translation from html to docx. (If you want a doc file rather than docx then replace "docx" with "doc" in the filePathOut definition and replace 16 with 0 in the SaveAs line. See wdSaveFormat Enumeration.)

library(RDCOMClient)

filePathIn <- file.path(getwd(), "mt.html")
filePathOut <- sub("html$", "docx", filePathIn)

w <- COMCreate("Word.Application")
doc <- w[["Documents"]]
od <- doc$Open(filePathIn)
od$SaveAs(filePathOut, 16)
w$Quit()

Upvotes: 4

Ghose Bishwajit
Ghose Bishwajit

Reputation: 342

Here is a simplistic way to store regression outputs:

sink("myresult.doc", append=T)

All outputs will be appending automatically as long as this is specified: append=T

HTH

Upvotes: 0

Related Questions