Creating Word Processor Tables from R Dataframes

A friend mentioned to me earlier this week that her students in an R-based statistics course would benefit from being able to create Word-compatible (i.e., .docx)

The function below also should work with LibreOffice’s .odt format.
tables from the output of their exercises. Having used pandoc, a valuable tool for converting between document file formats; and knitr, an R library for processing RMarkdown and $\LaTeX$ input; I wrote the following function for creating a docx (or odt, or rtf, or pdf, etc.) table from an R dataframe:

table_to_docx <- function(dataframe_to_use, temporary_markdown_file_to_write = "kable_output.mkd", output_format="docx") {
    if (!require('knitr')) {
        print("Sorry, you need to install the knitr package first. You may also need to install Pandoc (http://johnmacfarlane.net/pandoc/) separately.")
    }
    else # If the require() above worked...
    {
        # Create a Pandoc-flavored markdown-style table from a dataframe
        markdown_table <- kable(dataframe_to_use, format="pandoc", output=FALSE)
        
        # Write that markdown table to a temporary file:
        write(markdown_table, temporary_markdown_file_to_write)
        
        # Create a docx file from the temporary markdown file.
        # Documentation on more options can be found at http://yihui.name/knitr/demo/pandoc/
        pandoc(temporary_markdown_file_to_write, format=output_format)
    }
} # End of function table_to_docx

This function can be called with, e.g., table_to_docx(my_dataframe) to write a file called “kable_output.docx” to the working directory.

In R, the working directory can be seen with getwd(), and can be set with setwd('/path/to/directory').
It will also write a file in Markdown format as part of this process. Alternatively, one could use table_to_docx(my_dataframe, temporary_markdown_file_to_write="My_Output.mkd", output_format="odt") to write an odt-format file called “My_Output.odt” (along with a temporary file called “My_Output.mkd”). This is just a wrapper for knitr’s built-in pandoc functionality, but it’s modular and ready-to-go.

Related

Next
Previous