Sunday, December 11, 2011

R -> output to CSV -> Latex -> pdf (CSV -> Latex -> pdf)

Update: My friend pointed out that there are in fact several ways of including the output of R into a tex file. However what I'm using now is the package csvtool.

I would like to carry out data analysis in R and generate pdf files using Latex which include the results of the analysis.  

The issue: For graphics, one option is to save the figures as eps files in R (for e.g. by using postscript() command) and to include them in the final pdf file through Latex. What about other numerical results ? One option is to calculate the output (for e.g. the values of some variables) then copy those values from R into the Latex file. How ever I do not want to copy-paste them. I would like to run some R script, generate some results, and then run Latex which will pick up those results and create the pdf file. 

A solution: In R export the results as a csv file (for e.g. using the write.csv() command). I find it best to first put the results in a tabular form and then write it to the csv file. Then using Latex include this csv file in the final pdf output as a table with the command  \DTLdisplaydb{file_name}, which is available in the datatool package(\usepackage{datatool}). If the table is large and runs out of the page (in the portrait page setting), you can consider rotating the table by 90 degrees with the \begin{sidewaystable} ... \end{sidewaystable} command available in the rotating package. 


So basically something of this sort in Latex:
.
\usepackage{datatool}
\usepackage{rotating}

.
\DTLloaddb[noheader,keys={},headers={}]{}{} % Look up the documentation for command options
.
\begin{sidewaystable}[] % Look up the documentation for command options
\centering \caption{}
\DTLdisplaydb{file_name}
% Look up the documentation for command options
\end{sidewaystable}
.

Note: There are macros available for MS-Excel using which you can select a table in Excel and generate the corresponding Latex commands. However for that you will have to open the csv file first in MS-Excel.

1 comments:

mercurialmadnessman said...

Sweave seems much easier