在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子檔案程序的範例,依照knitr文檔yihui.name/knitr/demo/child。

首先是我稱為「knitr01.Rnw」的新主文件

\documentclass{article}

\begin{document}

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

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

<<>>=
dataset<-mtcars
@

<<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{Repeated table}
\end{table}

當首先通過“knit”運行,然後通過“pdflatex”運行時,結果是

在此輸入影像描述

為了繼續演示的完整性,這也允許子文件輸入孫子文件。

knit01.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)  
@

輸出是: 在此輸入影像描述

相關內容