Exporting R output to MS-Word with R2wd (an example session)

UPDATE (2014-11-02): please note that this post is from 2010. These days, it is much simpler to create docx files from R using knitr+pandoc. Using pander (links: [1], [2]) can also help make the markdown output look nicer in the file.

Creating reports is one of the basic tasks in data analysis. R provides numerous functions and packages to export it’s (beautiful) output and help compile it into a report.

In this post I will present one such (basic) solution for Windows OS users for exporting R output into Microsoft Word using the R2wd (package). There are more ways and strategies for doing this, and if encouraged by comments, I will gladly write more on the subject.
* * *

R to Word using {R2wd}

The package R2wd (available through CRAN) relies on rcom. It is a wrapper that uses the statconnDCOM server to communicate with MS-Word via the COM interface.

R2wd can perform the basic tasks you would expect to need when creating a report from R. It allows you to:

  • Create a new Word file
  • Create headers and sub-headers
  • Move to a new pages in the document
  • Write text
  • Insert tables (that is “data.frame” and “matrix”objects)
  • Insert plots
  • Save and close the Word document
  • …(and more)

The current R2wd can still be seen as being in BETA stages.  Some features are not yet available, such as:

  • Choosing text font (which means most of us will need to manually change the font in the document to “couriers new…”, in order for the formatting to look good)
  • Inserting of complex object outputs (such as summery.lm, although in the example bellow I show how that can be achieved using a simple function)
  • Speed – the speed of inserting a table is somewhat slow, I am not sure how it would scale to large documents

But from a (pleasant) correspondence with the package developer, I was assured the next release will supply us with more options and features.

R2wd package developer, Christan Ritter, invites feedback from users.  So if you have features you are missing in this packages, I believe he would like to know about it (you can e-mail Christan at:     christian.ritter <-at-> ridaco <-dot-> be  )

Getting R2wd 1.3

The current version of R2wd is 1.1 and Christan Ritter (the package developer), says it is a “first idea” and that a more elaborate version will soon (e.g: around July) be available on CRAN.   In the meantime, Christan was so kind as to send me a more recent version of the package, which you (until it gets uploaded to CRAN), you are welcome to download from here:
R2wd 1.3 download link

How to use R2wd to create a report – a sample session

Being young doesn’t prevent from R2wd to do some nice things.

Here is the text from the library(help=R2wd) :

If Word is not already running, wdGet() opens a new Word document, otherwise, it establishes a COM handle to the instance which is already running. The functions wdTitle, wdHeader, wdBody, and wdParagraph can be used to inject text elements into Word. Moreover, bookmarks can be added via wdInsertBookmarks and wdGoToBookmark allows to navigate among the bookmarks which also exist. There is another set of convenience functions, wdSection, wdSubsection, and wdSubsubsection which insert headers of level 1, 2, or 3, start new ’Sections’ in Word, and add bookmarks.
Graphs and dataframes can be inserted intoWord, by the wdPlot, wdTable commands. The wdTable command takes a dataframe or an array as arguments, creates a Word table of the appropriate dimensions and injects the content of the dataframe or array into it. It then formats the table in Word using elementary formating elements.
The functions wdApplyTheme and wdApplyTemplate allow to work with themes and templates.

Here is an example sessions to demonstrate some of what is said:

# install.packages("R2wd")
# library(help=R2wd)
require(R2wd)


wdGet(T)	# If no word file is open, it will start a new one - can set if to have the file visiable or not
wdNewDoc("c:\This.doc")	# this creates a new file with "this.doc" name

wdApplyTemplate("c:\This.dot")	# this applies a template


wdTitle("Examples of R2wd (a package to write Word documents from R)")	# adds a title to the file

wdSection("Example 1 - adding text", newpage = T) # This can also create a header

wdHeading(level = 2, "Header 2")
wdBody("This is the first example we will show")
wdBody("(Notice how, by using two different lines in wdBody, we got two different paragraphs)")
wdBody("(Notice how I can use this: ' n' (without the space), to  n  go to the next
		line)")
wdBody("האם זה עובד בעברית ?")
wdBody("It doesn't work with Hebrew...")
wdBody("O.k, let's move to the next page (and the next example)")

wdSection("Example 2 - adding tables", newpage = T)
wdBody("Table using 'format'")
wdTable(format(head(mtcars)))
wdBody("Table without using 'format'")
wdTable(head(mtcars))


wdSection("Example 3 - adding lm summary", newpage = T)

## Example from  ?lm
ctl

Update:
Upon reading my post, Chris suggested that I’ll also add a note here about SWORD, a tool written by Thomas Baier (the creator of the StatconnDCOM server) which allows to include R-code in a Sweave-like fashion in Word documents. Here is a link to the project: http://rcom.univie.ac.at

35 thoughts on “Exporting R output to MS-Word with R2wd (an example session)”

  1. I do not have Word on all my computers but I do have openoffice and Google Docs on all my computers. I have been eyeing Latex and sweave offerings but have been reluctant to sink the time into learning them. OpenOffice can read Microsoft Word docs. Can one use R2wd or do you have any other suggestions.

    I am head in study in which we frequently have to report data. The study is ongoing so any analysis I do now will have to be repeated. I want to be able to draft a report (that a non-nerd could read and be guided through) now that is automatically updated whenever there is new data. Any suggestions?

    1. Hi Farrel,

      One option is to go with Bernd suggestion.

      Another is to try R2wd with a connection to open office.
      I think the package to allow that is ROOo, which is available to download here:
      http://rcom.univie.ac.at/download.html
      And see if it works.
      If it does (which I doubt), then great.
      If not – we can contact the package developer and see if he might include the integration in for a next release.

      Good luck,
      Tal

    1. Thanks Ernesto,
      It is worth mentioning that Inference is NOT GPL, nor is it a free software.

      Yet thanks for sharing the link, it is worth seeing what solutions they found to be working 🙂

      Best,
      Tal

      1. You are right Tal. If you work for an academic institution, however, you can get for free.

  2. very helpful!!! i was wandering if there is a way to paste ps/pdf/… files that where not produced by R to MS word
    thanks

  3. Hello, I was succesfully installed and ran R2wd in my old lap, but now I have a windows 7 64bits with Microsoft Office 2010.

    Due to all these version changes I have not idea what is spoiling R2wd.

    R version is suppose to be fine. It is 2.11.1.

    What could you suggest me?

    Thanks a lot!
    Leticia

      1. Hello Tal,

        I installed statconnDCOM yesterday but now, when typing library(R2wd) the package again asks me to install it with installstatconnDCOM().

        Once I redid this I called R2wd and when I entered wdGet() I obtained:
        Error in wdGet() : attempt to apply non-function

        Do you think the communication is not possible because I have R 64-bit (in C:Program Files) and statconnDCOMM is installed in C:Program Files (x86)statconnDCOM ?

        Thanks
        Leticia

        1. I just tried to run R2wd on an x86 machine. When I type in

          wdGet()

          I also get the message

          Error in wdGet() : attempt to apply non-function

          So I don’t think it is x64-specific problem

          Thanks
          Brendan

  4. Hello I just ran the StatConnector Test and when pushing “Start R” I obtain the error text box:
    “Method ‘~’ of object ‘~’ failed”

  5. The latest (12th March 2012) work-around which I could get is as follows:
    Download and install statconnDCOM3.3-0B2_Noncommercial.exe from http://rcom.univie.ac.at/ and install the same. Invoke R thereafter (I have win-32/ 64 version 2.14.1 for Windows. Things work smoothly thereafter… Best wishes..

  6. How would you combine text and output in R2wd? I’m particularly interested in how you would for example say something like
    wdBody( “The sample size is ” nrow(data) “.”)

      1. Tried various things….

        #install.packages(“R2wd”)
        #library(help=R2wd)
        #install.packages(“rcom”)
        #library(rcom)
        #install.packages(‘R2wd’, dependencies = TRUE)
        require(R2wd)
        require(rcom)

        ## Not run:
        ## rcom needs to be installed
        if (!require(rcom)) warning(“Install rcom first”)
        ## This initializes the hook to Word
        ## if Word is already running it connects to it via StatconnDcom
        ## if not, it uses StatconnDcom to open word to create a new document
        ## and to connect to it.
        wdGet(T)  # If no word file is open, it will start a new one – can set if to have the file visiable or not
        wdNewDoc(“E:/CPR/trial.doc”) # this creates a new file…… ETC

        It gives the same error… 

  7. I have a matrix of 100 items. When I try to create a table, it only shows the first 6 rows. Can you please help with the code to get a 100 item table using R2wd?

    Thanks

  8. Hi! I have troubles using wdGet; the error tha shows up is:
     if (wdapp[[“Documents”]][[“Count”]] == 0) wdapp[[“Documents”]]$Add() : the argument has length zero.

    And I am not understanding my mistake.

    Thanks

  9. There is a very simple way to get a neat table, matrix, or data.frame from R into a table in your word processor. I use this with LibreOffice (the free office package based on openoffice). I assume it will easily work with Microsoft Word as well.

    1) Save your table, matrix, or data.frame as a csv. Below, I give an example:

    # first create a matrix (of course, you will have one already). 

    x=matrix(ncol=5,nrow=20)
    write.csv(x,file=”mytable.csv”)

    That is it on the R side!!!

    2) Now, open your csv file (which is a comma separated spreadsheet, look it up on wikipedia) in your spreadsheet program (localc or excel, etc).

    3) Select the part of the spreadsheet you want as a table (copy, control-c)

    4) Now go to your word processor. In LibreOffice, from the menu, select “edit” and then “paste special”. Paste special has various options. You do not want it as a spreadsheet object, but you want a real table, so you need to select “RTF” (in my libreoffice, that is somewhere at the bottom of the list).

    Of course, then you start with a basic table, it is easy to make it neat in your word processor.

    Alternatively, there is the RTF package for R, but I found that this did not always worked, and find the write.csv much easier and quicker.

  10. Is there any way to easily READ a ms word .doc file with R?

    I have several of them, only containing Text. No images, no important formatting. scan doesn’t get it, I tried a couple of encodings, but what I get ist something like

    Read 1 item
    [1] “ÐÏ21ࡱ”

  11. Hi.. I’m new here in R program. I was succesfully installed R2wd packages and when i entered wdGet() I obtained:
    “loading required package: rcom.
    error: exception occcured.
    Warning messages:
    1. In wdGet() : The package rcom is unavailable
    2. In wdGet() : Using RDOMClient package instead of rcom”
    I installed RDOMClient packages without any problems but still error for wdGet(). For rcom packages, I couldn’t find it in R 32-bit.
    Thank you.

Leave a Reply to Tal GaliliCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.