[Tex/LaTex] How to use a table generated by Latex in R(xtable)

rxtable

I have a LaTeX table generated by Excel. I want to place this table but not as a LaTeX code, but rather as a xtable. It is possible to convert LaTeX to xtable?

Best Answer

Set by step: Suppose that you have a file.xlsx that look like:

Excel file

To convert to R, first export to file.csv:

,apples,tomatoes,babanas
Jinks,3,12,15
Pixie,4,5,6
Dixie,2,8,9

Then import as a data frame mytable in R:

> mytable <- read.table("file.csv", header=TRUE, sep=",") 
> mytable

      X apples tomatoes babanas
1 Jinks      3       12      15
2 Pixie      4        5       6
3 Dixie      2        8       9

Or import directly from the file.xlsx (need Perl installed on your system):

> library(gdata) 
> mytable  <- read.xls("file.xlsx")  

The data frame obtained must be the same in any case. Just in case that first column are really row names as above:

> rownames(mytable) <- mytable[,1]
> mytable[,1] <- NULL
> mytable

      apples tomatoes babanas
Jinks      3       12      15
Pixie      4        5       6
Dixie      2        8       9

For convert the dataframe mytable as a xtable (that is, a chunk of LaTeX code):

> library(xtable) 
> xtable(mytable)

% latex table generated in R 3.1.1 by xtable 1.7-4 package
% Wed Mar 11 06:11:44 2015
\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
  \hline
 & apples & tomatoes & babanas \\ 
  \hline
Jinks &   3 &  12 &  15 \\ 
  Pixie &   4 &   5 &   6 \\ 
  Dixie &   2 &   8 &   9 \\ 
   \hline
\end{tabular}
\end{table}

So you can copy & paste the ouput of R in your LaTeX file to obtain:

MWE2

But the good thing of LaTeX+R is that you can make all the above automatically inserting a R chunk in your file.tex document (now is R noweb document, so save it as file.Rnw) and compile it using Sweave or knitr from the command line (see How to build Knitr document from the command line ) or simply making in Rstudio:

File > New file > R Sweave > Write some like:

\documentclass[twocolumn]{article}
\usepackage{titlecaps}
\usepackage{lipsum}
\title{Owners {\it \&} Fruits}
\author{Fran}
\begin{document}
\maketitle
<<mytable,echo=FALSE,warning=FALSE,message=FALSE,results='hide'>>=
library(gdata) 
mytable  <- read.xls("file.xlsx")
rownames(mytable) <- mytable[,1]
mytable[,1] <- NULL
library(xtable) 
@
\section*{Introduction}
The cartoons (\Sexpr{row.names(mytable)}) are shooting fruits (\Sexpr{names(mytable)}). 
\lipsum[2] 
\section*{Cartoons have \Sexpr{sum(mytable$apples)} apples}
\lipsum[3]
<<xtable,echo=FALSE,warning=FALSE,message=FALSE,results='asis'>>=
print(xtable(mytable, caption="My Excel table"), caption.placement = "top")
@
\lipsum[4-15]
\end{document}

and finally, click on Compile PDF and you will obtain this file.pdf:

MWE

Related Question