[Tex/LaTex] Input Tex file in knitr file

knitr

I am showing a simple example here just to frame the question.

\documentclass{article}

\begin{document}

<<>>=
library('ggplot2')
dataset <- diamonds
@

\begin{table}[htbp]
  \centering
  \begin{tabular}{c|c|c|c}
  \textbf{Name} & \textbf{Columns} \\\hline \hline
  dataset & \Sexpr{length(colnames(dataset))} \\
  \end{tabular}
  \caption{Repeated table}
\end{table}

\end{document}

Now I am repeating this table (exact table) multiple times over the file. (Imagine replacing dataset with another set before calling this table).

\documentclass{article}

\begin{document}

<<>>=
library('ggplot2')
dataset <- diamonds;
@

\input{table-file.tex}

\end{document}

I am putting the entire tabular part into this file, and then input it several places. But I can't get this to work. I was wondering if this is possible? any better approaches to make this table "modular".

Thanks

Best Answer

Here is an example using the knitr child file process as per the knitr documentation yihui.name/knitr/demo/child.

First the new main file which I called 'knitr01.Rnw'

\documentclass{article}

\begin{document}

<<>>=
library('ggplot2')
dataset <- diamonds
@

<<child='child-knitr01.Rnw'>>=
@

<<>>=
dataset<-mtcars
@

<<child='child-knitr01.Rnw'>>=
@
\end{document}

Note that I inputed the child twice each with a different dataset.

And the child file which I named 'child-knitr01.Rnw'.

\begin{table}[htbp]
  \centering
  \begin{tabular}{c|c|c|c}
  \textbf{Name} & \textbf{Columns} \\\hline \hline
  dataset & \Sexpr{length(colnames(dataset))} \\
  \end{tabular}
  \caption{Repeated table}
\end{table}

When run first through 'knit' and then through 'pdflatex' it results in

enter image description here

To continue the demonstration for completeness, this also allows child files to input grandchildren.

The knitr01.Rnw is changed as follows.

\documentclass{article}
\begin{document}
<<>>=
library('ggplot2')
dataset <- diamonds
title="These are diamonds"
@

<<child='child-knitr01.Rnw'>>=
@

<<>>=
dataset<-mtcars
title="These are cars"
@

<<child='child-knitr01.Rnw'>>=
@

\end{document}

Here is the revised 'child-knitr01.Rnw' file

\begin{table}[htbp]
  \centering
  \begin{tabular}{c|c|c|c}
  \textbf{Name} & \textbf{Columns} \\\hline \hline
  dataset & \Sexpr{length(colnames(dataset))} \\
  \end{tabular}
  \caption{\Sexpr{paste(substr(capture.output(print(title)),5,50))}}
  % The 5 is to remove some leading R stuff (try with 1 to see why)
  % The 50 is chosen to be longer than the string
\end{table}

<<child='grand-child-knitr01.Rnw'>>=
@

And here is the 'grand-child-knitr01.Rnw' file

Demonstration that you can call on 'grandchildren' files with knitr.

<<>>=
names(dataset)  
@

And the output is: enter image description here

Related Question