//
you're reading...
How-to, Latex, R, Uncategorized

Generate Latex tables from R data frames

When writing reports using R + Latex environment it’s a good idea to directly generate the tables containing results
of your calculations directly from R. This is rather a straightforward task when using commands like latex.

One place when this gets a bit awkward is when you want to include some math in e.g. column names.
A simple trick that seems to work pretty well is to map your column names just before generating the latex table.
This can be done using the hash package like so:

require(Hmisc)
require(hash)

# Some data for our table
x <- 1:5
df <- data.frame(x=x, x2=x^2,x3=x^3, x0.5=sqrt(x))


# First version - without mapping
a <- latex(df ,rowlabel="",file="table.tex")


# Second version - column names mapped using a hash object
map <- function(vals){
  col.map <- hash( x = "$x^1$",
    x2 = "$x^2$",
    x3 = "$x^3$",
    x0.5 = "$\\sqrt x$")

  lapply(vals, function(v)col.map[[v]])
}

colnames(df) <- map(colnames(df))
a <- latex(df, rowlabel="", file="table.mapped.tex")

After including the generated tex files in some Latex document the table without the mapping looks like this
table

… and using mapped column names we have:
mappedTable

About these ads

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: