10

Is there an easy way to automatize the conversion of a R dataframe to a pretty Word table in APA format for publishing manuscripts? I'm currently doing this by saving the table in a csv, opening that in excel, copying the excel table to Word, and formatting it there, but I'm hoping there would be a way to automatize the formatting in R, so that when I convert it to Word, it would already be in APA format, because Word sucks in automatization.

Basically, I want to continue writing the manuscript itself in Word, while doing my analyses in R. Then gather all the results in R to a table (with manually modifiable formatting) by a script and convert it to whatever format I could then simply copy-paste to Word (so that the formatting actually holds). When I need to modify the table, I would make the changes in R and then just run the script again without the need to do any changes in Word.

I don't want to learn LaTeX, because everyone in my field uses Word with features like track changes, and I use Zotero add-in for citations, so it's simpler to just keep the writing separate from the analyses. Also, I am a psychologist, not a coder, so learning a lot of new technologies just for this is probably not worth the effort for me. Typically with new technologies come new technical problems, and I am aiming to make my workflow quicker, but not at the cost of unpredictability (which may make it slower exactly at the moment when I cannot afford it).

I found a R+knitr+rmarkdown+pander+pandoc solution "with as little overhead as possible", but it seems to be quite heavy still because I don't know any of those technologies apart from R. And I'm not eager to start learning all that, as it seems to be aimed for doing the writing and all in R to the very end, while I want to separate my writing and my code - I never need code in my writing, only the result tables. In addition, based on the examples, it seems to fetch the values directly from R code (e.g., from summary() to create a descriptive table), while I need to be able to tinker with my table manually before converting it, for instance, writing the title and notes (like a specific note to one cell and explaining it in the bottom). I also found R2wd, but it seems to be an older attempt for the same "whole workflow in R" problem as the solution above. SWord does not seem to be working anymore.

Any suggestions?

RandomMonitor
  • 439
  • 1
  • 8
  • 16
  • you can use kable from knitr `library(knitr)` `kable(mtcars, format = "html")` then paste it into word. – jeremycg Aug 14 '15 at 13:39
  • Recommend a library questions are off-topic, so voting to close. There are a lot of choices. You can also look at https://cran.r-project.org/web/packages/rtf/index.html. Personally, in this situation I use `brew` with `xtable` to generate an HTML version and use [Word style derived CSS](http://superuser.com/questions/148884/is-there-a-way-to-export-word-styles-as-css) with copy and paste. – A. Webb Aug 14 '15 at 13:41
  • There is the apaTables package nowadays, which exports model summary tables directly to Word https://cran.r-project.org/web/packages/apaTables/index.html . You can also do this with Rmarkdown and its extensions (https://stackoverflow.com/questions/37671868/knitr-rmarkdown-docx-tables), although the direct export of a data.frame from R script to Word still seems to be lacking at the time of writing. This field has taken huge steps forward since 2015. It would be good to let the community to write an updated answer to this question. – Mikko Nov 08 '19 at 07:46

3 Answers3

8

(Just to let you know, I am the author of the packages I recommend you...)

You can use package ReporteRs to output your table to Word. See here a tutorial (not mine): http://www.sthda.com/english/wiki/create-and-format-word-documents-using-r-software-and-reporters-package

Objects FlexTable let you format and arrange tables easily with some standard R code. For example, to set the 2nd column in bold, the code looks like:

myFlexTable[, 2] = textBold()

There are (old) examples here: http://davidgohel.github.io/ReporteRs/flextable_examples.html

These objects can be added to a Word report using the function addFlexTable. The word report can be generated with function writeDoc.

If you are working in RStudio, you can print the object and it will be rendered in the html viewer so you can export it in Word when you are satisfied with its content.

You can even add real Word footnotes (see the link below) http://davidgohel.github.io/ReporteRs/pot_objects.html#pot_footnotes

If you need more tabular output, I recommend you also the rtable package that handles xtable objects (and other things I have to develop to satisfy my colleagues or customers) - a quick demo can be seen here:

http://davidgohel.github.io/tabular/

Hope it helps...

David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • Thanks! But it seems that ReporteRs is a similar attempt than R2wd and the markdown solution for handling the whole writing process in R, which is not what I'm for. The ability to print to the viewer within Rstudio in htmlTable is more like what I'm looking for than going through separate word files. Although if htmlTable is not able to manipulate the table further than the basics, I might be forced to look into this. – RandomMonitor Aug 19 '15 at 09:42
  • As written above `FlexTable` ARE displayed in the htmlViewer! – David Gohel Aug 20 '15 at 17:03
  • Just want to mention that `ReporteRs` package is not available now. It was rewritten without Java and now it calls `officer`. For more info see https://cran.r-project.org/web/packages/officer/vignettes/word.html – atsyplenkov Apr 14 '19 at 17:58
  • 1
    @atsyplenkov the link does not work anymore. Moreover, commands that were working in ReporteRs do not work on officer and Reporters is not available for recent versions of R (e.g. 3.6.2) – fabiob Jan 21 '20 at 16:11
7

I have had the same need, and I have ended up using the package htmlTable, which is quite 'cost-efficient'. This creates a HTML table (in RStudio it is created in the "Viewer" windows in the bottom right which I just mark using the mouse copy-paste to Word. (Start marking form the bottom of the table and drag the mouse upwards, that way you are sure to include the start of the HTML code.) Word handles these tables quite nicely. The syntax of is quite simple involving just the function htmlTable(), but is still able to make somewhat more complex tables, such as grouped rows and primary and secondary column headers (i.e. column headers spanning more than one column). Check out the examples in the vignette.

One note of caution: htmlTable will not work will factor variables, i.e., they will come out as integer numbers (according to factor levels). So read the data using stringsAsFactors = FALSE or convert them using as.character().

Including trailing zeroes can be done using the txtRound function. Example:

mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)

It is not completely straightforward to assign formatting soch as bold or italics, but it can be done by wrapping the table contents in HTML code. If you for instance want to make an entire column bold, it can be done like this (please note the use of single and double quotation marks inside paste0):

library(plyr)
mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)
txt$x <- aaply(txt$x, 1, function(x)
               paste0("<span style='font-weight:bold'>", x, "</span")
              )
htmlTable(txt)

Of course, that would be easier to to in Word. However, it is more interesting to add formatting to numbers according to some criteria. For instance, if we want to emphasize all values of x that are less than 0.2 by applying bold font, we can modify the code above as follows:

library(plyr)
mini_table <- data.frame(Name="A", x=runif(20), stringsAsFactors = FALSE)
txt <- txtRound(mini_table, 2)
txt$x <- aaply(txt$x, 1, function(x) 
               if (as.numeric(x)<0.2) { 
                  paste0("<span style='font-weight:bold'>", x, "</span>")
               } else {
                  paste0("<span>", x, "</span>")
               })
htmlTable(txt)

If you want even fancier emphasis, you can for instance replace the bold font by red background color by using span style='background-color: red' in the code above. All these changes carry over to Word, at least on my computer (Windows 7).

Dag Hjermann
  • 1,960
  • 14
  • 18
  • This solution seems simple enough for my purpose, but I have a couple of questions. First, it seems that when printing into the viewer, I lose the trailing zeros (they are still visible when printed in the console). Do you know how to stop that from happening? Second, is it possible to format the html table further in R? For instance, it would be useful to have certain cells bolded or notes added (with superscript letters). – RandomMonitor Aug 18 '15 at 13:53
  • @RandomMonitor Trailing zeroes is easy, you just wrap the table in the function `txtRound`(part of htmlTables). Mini example: `mini_table <- data.frame(Name="A", x=4, y=9, stringsAsFactors = FALSE); htmlTable(txtRound(mini_table, 2))`. Regarding extra formatting (e.g. bold), that is more difficult, but possible. I will update my answer. – Dag Hjermann Aug 20 '15 at 11:19
  • 1
    I do not think that the solution described here for bolding certain text is valid anymore. Instead of bolding the text in column `x`, it now simply prints the contents of the column between the formatting tags `` and ``. – graggsd Feb 27 '18 at 16:49
-1

The short answer is "not really." I've never had much luck getting well formatted tables into MS Word. The best approach I can offer you requires using Rmarkdown to render your tables into an HTML file. You can copy and paste you results from the HTML file to MS Word, but I make no guarantees about how well the formatting will follow.

To format your tables, you can try something like the xtable package, or the pixiedust package. But again, no guarantees that the formatting will transfer.

Benjamin
  • 16,897
  • 6
  • 45
  • 65