TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


     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
You can check this in LaTeX. See Expandable version of \InputIfFileExists or \IfFileExists. – Werner Jan 26 '13 at 3:39
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
up vote 4 down vote accepted

Put this into your preamble:


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



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}

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

Your Answer


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.