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


Question:

How do i handle situation where "xyplotFacSpecTotVarTest.pdf" doesn't exist. File generated off of contents in a table, which in turn may or may not have data. final PDF generation process errors if it is missing "xyplotFacSpecTotVarTest.pdf" How Can i handle this scenario ? I have tried /IfFileExist but it doesnt seem to working ..See following implementation.

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


## migrated from stackoverflow.comJun 5 '14 at 11:38

This question came from our site for professional and enthusiast programmers.

• You don't have \Sexpr{image_dir} in your \ifFileExists expression, so I assume the evaluation of the folder+filename doesn't work as expected. – Werner May 10 '14 at 5:21

Looking at the tags, I assume you use knitr. Why not let R itself (silently) determine if the file exists?

<<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")
}
@


Note the results='asis' chunk option. Each cat'd string will be outputted to the .tex file as it stands (hence the option's name). In other words, each cat'd string will be a LaTeX command to be compiled.

You can even generalize the above code by creating a fancy R function e.g. include_if_exists(filename), and reuse it in many chunks.