Getting tables from R output

[This article was first published on Dataninja » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Turning plain-text output into well-formatted tables can be a repetitive task, especially when many tests or models are being incorporated into a paper.

For R users, there are several methods that can make this task easier (though not much less repetitive), regardless of what typesetting system you use.

LaTeX tables
The xtable package produces LaTeX-formatted tables. Using xtable, specific kinds of R objects, such as linear model summaries, can be turned into “xtables”, which can in turn be output to either LaTeX or HTML.

To use:

  1. Install the xtable package: install.packages(“xtable”)
  2. Load the xtable package: library(xtable)
  3. Create an xtable for the object that you want to export: newobject<-xtable(object)
  4. Export your xtabled object to LaTeX: print.xtable(newobject, type=”latex”, file=”filename.tex”)

Options

  • To export to HTML instead of LaTeX, use type=”html” and use the .html extension in the filename
  • To have R produce the proper markup in the console (instead of writing in to a file) omit the file=filename option

Other word processors
If, instead of LaTeX, you are using Word, OpenOffice, NeoOffice, etc., there is a way to produce more easily formatted tables. Just follow these steps:

  1. Create an xtable, as above, and print the output to an HTML file: print.xtable(newobject, type=”html”, file=”filename.html”)
  2. Open the generated HTML file in your browser (may I recommend Firefox)
  3. Copy the table contents and paste them into your word processor
  4. Convert the text to a table: In OpenOffice or NeoOffice: Select the text and go to Tools: Text <-> Table and select “Tabs” as the delimiter. In Word: Select the text and go to Table: Convert: Convert Text to Table, and use separate text at tabs

This technique is somewhat more convoluted than creating pure LaTeX output, but it is probably quicker than entering the output by hand.

Note: An alternative to xtable is the R2HTML package, which works similarly, but does not require xtable objects to be created in order to generate HTML output.


To leave a comment for the author, please follow the link and comment on their blog: Dataninja » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)