Transforming a data.frame from R into a table in LaTeX

Inserting a table into LaTeX can sometimes be a very tedious job, especially when the table includes many data. But there is hope. A very easy way to transform a data.frame into LaTeX code is to use the xtable package. And here is how it works:

1) Let us create a random data frame to work with:

```{r}
data <- data.frame(
 base=sample(c('A','T','C','G'), size=25, replace=T), present=sample(c('T','F'), size=25, replace=T))
data
```
A very simple data.frame in R.
A very simple data.frame in R.

2) We need to load the xtable package

```{r}
install.packages('xtable')
library(xtable)

3) Now we simply use the xtable() function to create the LaTeX code for our table

```{r}
xtable(data)
```

4) It produces the ready to use LaTeX code that we can imediately copy and paste into our LaTeX file. xtable also offers to add information like the caption and a label or how many digets numbers should have. Let’s try this out and add a further column with random numbers to it.

```{r}
data2 <- data
data2$coefficient <- rnorm(n=25,mean=4,sd=1)
data2
```

 

xtable_3
xtable returns LaTeX code (without the ## at the beginning of the line) right inside your R console. Just copy it into a LaTeX document.

This is our new data frame. And now we create the LaTeX code including a caption and label (the label by the way is what you use in your text to refer to.)

```{r}
xtable(data2, caption='A table with important results', label='tab:important_results', digits=3)
```
xtable_4
This is what the table looks like after pasting the code into a simple LaTeX document.

Nice. The only problem is that xtable puts the caption below the table but in scientific work the caption of a table is always above the table (opposite for figures). Here is the pdf to this example: xtable_example