Reputation: 5270
Is there a way to generate tables in tex format in R and then call them in my *.rnw file I have to geenerate a lot of tables using some userdefined function and then use them in my latex file through sweave/knitr. Here is 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 as follows
latex(data1,file='myfile.tex')
When running the above in my sweave document R-studio was getting stuck in the sense that the process would not end. I get 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 guess there might be a better way. I do not not what mistake I am doing in the latex command. I would appreciate if someone can help me with this by providing me 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}
Upvotes: 3
Views: 403
Reputation: 32351
As suggested in the other answers, the easiest
(with Hmisc::latex
or xtable
)
is usually to generate the LaTeX code only when needed.
If this is not possible, the following should work:
tmp <- latex(data1,file='myfile.tex')
What happens is that latex
creates the file
and returns an object of class latex
.
The print
method is then called, but it tries to compile the file
and display the results, which is not desired in your case.
Assigning the result to a variable (which will not be used),
or wrapping the call in invisible
, suppresses the call to print
.
invisible( latex(data1,file='myfile.tex') )
Upvotes: 3
Reputation: 13280
You could use the xtable 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}
Upvotes: 3