Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'm working on Sweave and using includegraphics for include image in report dynamically.

Pseudocode:

 <<>
     for ( i to 100)   # run loop 1 to 100
     {
          includegraphics(image.i)    # include image in article.
     }
 @

In the above code I am adding 100 images using loop but I need to check that image.i exists or not first before including the image in report. Is there any way to check it first.

share|improve this question
5  
You can check this in LaTeX. See Expandable version of \InputIfFileExists or \IfFileExists. –  Werner Jan 26 '13 at 3:39
5  
In R, you also have the function file.exists() that you can use in the chunk if you prefer –  vaettchen Jan 26 '13 at 4:15
add comment

1 Answer 1

up vote 4 down vote accepted

Put this into your preamble:

\newcommand\includegraphicsifexists[2][width=\linewidth]{\IfFileExists{#2}{\includegraphics[#1]{#2}}{}}

Then you can can safely use the following, the only problem is that you always have to add the extension:

\includegraphicsifexists[width=\linewidth]{nonexistingfile.pdf}

-------------------------------------------------------------------

You can make a version that makes a whole figure appear or not depending on the file presence (again, this goes to the preamble):

% arguments: [parameters for includegraphics]{filename}[float placement]{caption}
\makeatletter
\def\FIF@nopl[#1]#2#3{\IfFileExists{#2}{\begin{figure}\centering
  \includegraphics[#1]{#2}\caption{#3}\end{figure}}{}}
\def\FIF@pl[#1]#2[#3]#4{\IfFileExists{#2}{\begin{figure}[#3]\centering
  \includegraphics[#1]{#2}\caption{#4}\end{figure}}{}}
\newcommand\FigureIfExists[2][width=\linewidth]{\@ifnextchar[%
  {\FIF@pl[#1]{#2}}%
  {\FIF@nopl[#1]{#2}}%
}

Notice that I consider [width=\linewidth] as a good default argument to \includegraphics but you might change it of course. The usage is simple:

\FigureIfExists{myfile.pdf}[!t]{Caption of this nice figure.\label{fig:myfile}}

\FigureIfExists[scale=0.3]{nofile.pdf}[p]{This figure won't exist,
  nor the label.\label{fig:nofile}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.