knitr ファイルに Tex ファイルを入力する

knitr ファイルに Tex ファイルを入力する

ここでは、質問を明確にするために簡単な例を示します。

\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}

ここで、このテーブル (正確なテーブル) をファイル上で複数回繰り返します (このテーブルを呼び出す前に、データセットを別のセットに置き換えることを想像してください)。

\documentclass{article}

\begin{document}

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

\input{table-file.tex}

\end{document}

表形式の部分全体をこのファイルに入れて、それをいくつかの場所に入力しています。しかし、うまくいきません。これが可能かどうか疑問に思っています。この表を「モジュール化」するためのより良い方法はありますか。

ありがとう

答え1

以下は、knitr ドキュメント yihui.name/knitr/demo/child に従って、knitr 子ファイル プロセスを使用する例です。

まず、'knitr01.Rnw'という新しいメインファイル

\documentclass{article}

\begin{document}

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

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

<<>>=
dataset<-mtcars
@

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

異なるデータセットを使用して、子を 2 回入力したことに注意してください。

そして、子ファイルは「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}

最初に「knit」を実行し、次に「pdflatex」を実行すると、結果は次のようになります。

ここに画像の説明を入力してください

完全性のためにデモンストレーションを続けると、これにより子ファイルが孫を入力することも可能になります。

knitr01.Rnw は以下のように変更されます。

\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}

修正された「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{\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'>>=
@

そして、ここに「grand-child-knitr01.Rnw」ファイルがあります

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

<<>>=
names(dataset)  
@

出力は次のようになります。 ここに画像の説明を入力してください

関連情報