Latex ifFileExist

Latex ifFileExist
\subsection{Checksum: Factor, Specific, and Total Variance}
Perhaps the most basic test of a regression model is if the factor and specific variances sum to equal the total variance.  Here, we 
present this diagnostic as an xy-plot, with the sum of factor and specific variance on the x-axis and the total variance on the y-axis.  We 
expect the plotted points to line up tightly along the identity line.

\clearpage
\begin{figure}[!h]

\centering

\includegraphics{\Sexpr{image_dir}xyplotFacSpecTotVarTest.pdf}

\caption{Total Variance vs. Sum of Factor and Specific Variance, All Instruments Passing Exposure Model.}

\end{figure}

问题:

如果“xyplotFacSpecTotVarTest.pdf”不存在,我该如何处理这种情况?文件是根据表中的内容生成的,而表中可能包含数据,也可能不包含数据。如果缺少“xyplotFacSpecTotVarTest.pdf”,最终 PDF 生成过程将出错。我该如何处理这种情况?我尝试过 /IfFileExist,但似乎不起作用。请参阅以下实施。

\IfFileExists{{image_dir}{xyplotFacSpecTotVarTest.pdf}} { 

\clearpage

\begin{figure}[!h]

\centering

\includegraphics{\Sexpr{image_dir}{xyplotFacSpecTotVarTest.pdf}}

\typeout{File Exist: xyplotFacSpecTotVarTest.pdf}

\caption{Total Variance vs. Sum of Factor and Specific Variance, All Instruments Passing Exposure Model.}

\end{figure} } 

{\typeout{File DOESNT Exist: xyplotFacSpecTotVarTest.pdf}}

答案1

查看标签,我假设您使用knitr。为什么不让 R 本身(默默地)确定文件是否存在?

<<chunkname,results='asis',echo=FALSE>>=
if (file.exists(file.path(image_dir, "xyplotFacSpecTotVarTest.pdf"))) {
   cat("\\clearpage\n")
   cat("\\begin{figure}[!h]\n")
   # and so on
}
else {
  cat("\\textbf{File does not exist.}\n\n")
}
@

注意results='asis'chunk 选项。每个cat'd 字符串将按原样输出到文件.tex(因此得名)。换句话说,每个cat'd 字符串都将是要编译的 LaTeX 命令。

您甚至可以通过创建一个奇特的 R 函数(例如)来概括上述代码include_if_exists(filename),并在许多块中重复使用它。

相关内容