Including some tex-formatted tables in my main document
Is there a way to generate tex-formatted tables in R and then call them in my * .rnw file I have to generate many tables using some user-defined function and then use them in my latex file via sweave / knitr. Here's a simplified example to illustrate my point ...
Data:
x1 <- round(rnorm(10),2)
x2 <- sample(c('a','b','c'),10,replace=TRUE)
data1 <- cbind(x1,noquote(x2));data1 <- as.data.frame(data1)
names(data1)=c('X1','X2')
Now I want to put this data1
in a tex file like this
latex(data1,file='myfile.tex')
When run above in my doc, sweave R-studio gets stuck in the sense that the process won't end. I am getting the following error:
No file file1170690e2c79.aux.
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
[1] (C:\Users\~~~\AppData\Local\Temp\RtmpeuvW08\file1170690e2c79.aux) )
Output written on file1170690e2c79.dvi (1 page, 604 bytes).
Transcript written on file1170690e2c79.log.
So, I used the following
sink('myfile.tex')
latex(data1,file='')
sink()
I think there might be a better way. I don't know what mistake I am making on the latex team. I would appreciate if someone can help me with this by providing me with a better approach
Here is my sweave file
\documentclass{article}
\usepackage{ctable}
\title{Untitled}
\begin{document}
\maketitle
<<somechunk,results=tex,echo=FALSE>>=
x1 <- round(rnorm(10),2)
x2 <- sample(c('a','b','c'),10,replace=TRUE)
data1 <- cbind(x1,noquote(x2));data1 <- as.data.frame(data1)
names(data1)=c('X1','X2')
sink('myfile.tex')
latex(data1,file='')
sink()
@
Here is my table 1 \include{myfile}
\end{document}
source to share
As suggested in other answers, the simplest one (with Hmisc::latex
or xtable
) will usually generate LaTeX code only when needed.
If this is not possible, the following should work:
tmp <- latex(data1,file='myfile.tex')
What happens is what latex
creates the file and returns the class object latex
. The method is then called print
, but it tries to compile the file and display the results, which are not desired in your case. Assigning the result to a variable (which will not be used), or ending the call in invisible
, suppresses the call print
.
invisible( latex(data1,file='myfile.tex') )
source to share
You can use the xxtable package:
\documentclass{article}
\usepackage{ctable}
\begin{document}
<<somechunk,results=tex,echo=FALSE,results=hide>>=
library(xtable)
x1 <- round(rnorm(10),2)
x2 <- sample(c('a','b','c'),10,replace=TRUE)
data1 <- cbind(x1,noquote(x2));data1 <- as.data.frame(data1)
names(data1)=c('X1','X2')
@
Here is my table 1:
<<results=tex, echo=FALSE>>=
xtable(data1)
@
\end{document}
source to share