Is there a way to easily turn a data frame into a Word table via rmarkdown?
If I use rmarkdown in RStudio to create a Word document I get a nicely printed table but
You can use the rmarkdown
and knitr
packages. Here is an example function, where df
is the data.frame
, output_file
is the output file name and output_dir
the output folder. Extra named argument are sent to rmarkdown::render
:
df2word <- function(df, output_file = "table.doc", output_dir = ".", ...) {
f <- tempfile(fileext =".Rmd" )
cat(file = f, '```{r, echo = FALSE}
knitr::kable(df)
```', append = TRUE)
rmarkdown::render(f, output_file = output_file, output_dir = output_dir, ...)
unlink(f)
file.path(output_dir, output_file)
}
out <- df2word(mtcars)
browseURL(out)
Of course you can adapt the code to be more flexible.
It is though flexible enough to allow you to extract other formats too, e.g. html:
out <- df2word(mtcars, output_file = "table.html")
browseURL(out)
or pdf:
out <- df2word(mtcars, output_file = "table.pdf", output_format = rmarkdown::pdf_document())
browseURL(out)