Saturday, 17 January 2015

R Package Spotlight - xtable

xtable is an R package on CRAN that converts output into LaTeX code for a table of that output.

For writing papers, it has cut the time it takes to produce and manage a table by a factor of 3 or 4.

Here's some example code

## Install and load 

## Get 10 random rows from the Iris dataset
theseRows = sample(1:nrow(iris), 10)
theseRows = sort(theseRows)
dat = iris[theseRows,]

### Make a LaTeX table of the data and print to screen

...and you have a basic table. From there you can make edits to the table in LaTeX, but I recommend doing more formatting with xtable first. You specify some parameters in the call to xtable().

### Print the LaTeX table code with more precision and a caption
xtable(dat, digits=4, caption="Ten lines from Iris")

If you store the xtable object as a variable rather than printing it out right away, you can change or retrieve xtable parameters.

### Make a LaTeX table of the data and save as "xt"
xt = xtable(dat, digits=4, caption="Ten lines from Iris")

## Check the default column alignments

## Change the alignments and add a vertical break after the 3rd column
align(xt) = "clr|clr"

## Change the caption
caption(xt) = "Dinner menu for goats"

With a stored xtable object, you can specific a wider variety of parameters with print(). Note that the row names are considered to be the first column, so the LaTeX code that comes out of print(xt, ... ) will have lr|clr in its alignment specification, not clr|clr

print(xt, include.rownames=FALSE)

For more details, see the xtable reference manual on CRAN.

No comments:

Post a comment