[Tex/LaTex] Embedding knitr tex files on a bigger latex file

knitr

There are already some question about about how to use Knitr's latex output within a new knitr document, using Rstudio and include or input and declaring some chunks as child.

But what if I want to use a simple knitr output (such as an R xtable) from within an external LaTeX program, such as TeXStudio to build a larger project?

For example, I could create a mytable.rnw file and generate this simple table

\documentclass{article}
\begin{document}

<<r table2, results='asis', message=T, echo=F>>=

library(xtable) 
print(
  xtable(
    head(iris),
    caption = 'Iris data'
  ),
  comment = FALSE,
  type = 'latex'
)

@

\end{document}

enter image description here

And now I want to grab the generated mytable.tex file and use it in a bigger document from TexStudio, in the same folder.

\documentclass{article}
\begin{document}
 First table:
 \include{mytable}
 Second table:
 \include{mytable}
\end{document}

(Maybe is better to use input)
When I try to compile it I get many errors:

Can be used only in preamble. \documentclass
Can be used only in preamble. \documentclass{article}\usepackage
Can be used only in preamble. ...ss{article}\usepackage[]{graphicx}\usepackage
Undefined control sequence. \definecolor
Can be used only in preamble. \usepackage
Undefined control sequence. \definecolor
Undefined control sequence. \definecolor
Undefined control sequence. \definecolor
Undefined control sequence. \definecolor
Can be used only in preamble. \usepackage
Can be used only in preamble. ...eExists{upquote.sty}{\usepackage{upquote}}{}
Can be used only in preamble. \begin{document}

I guess the problem arises because knitr ouput includes a lot of preamble information that can't be included within the document body, not only usepackage directives but also a lot of fie-tune information about colors, tables…

What's the proper way do it?
How to force Rstudio's knitr to output only the proper information?
Or how to force my main latex document (from TexStudio) to correct the problem?

If we have to do it many times is there any easy way to include that preamble in the main tex document without going manually one by one.
Or even worse, some genetared outputs may contain incompatible preambles.

Best Answer

The easiest way to do it, would be to make your main document also a .Rnw file, that could contain nothing but LaTeX (at first).

Within the main .Rnw document you could do something like

<<child="myTable.Rnw">>=
@

where myTable.Rnw can be any .Rnw file that does not include header information, e.g. your example document without documentclass and begin{document}/\end{document}

Of course you could just as well include the r-chunk from myTable.Rnw in to the main document (as well as other r-chunks).