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}

다른 데이터 세트를 사용하여 하위 항목을 두 번 입력했습니다.

그리고 '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)  
@

출력은 다음과 같습니다. 여기에 이미지 설명을 입력하세요

관련 정보