I am new to sweave and Latex. I am basically using an if-else loop which should display some specific image (taken from the laptop) if certain condition is satisfied. When I run this loop in R, the output is satisfactory in the console. It is also alright when I use "compile pdf" button on top in an Rnw file.

However, I need to produce different reports for each row of a csv, so I use a separate run file where I loop the Rnw through each row of the csv and produce multiple reports (one for each row). This works fine for text based output. But, this does not display the images if I loop through it. Here's a sample of what I have written for this:

<<echo=FALSE, fig.show='asis', fig=T>>=
image1 <- image_read(path)
image2 <- image_read(path)
x <- 3
if (x >=0 && x <=2){
    #should display image1
}else if (x>=3 && x<=4){
    #should display image2

\end {figure}

To show the images, I tried using print, paste, knitr::include_graphics but none worked for me. I am not sure whether it is a latex problem or an R problem and hence unable to find an appropriate solution. Any help would be sincerely appreciated. If you require a sample of the run file I mentioned, I shall be glad to share it. Thank you!

1 Answer 1


This should work with knitr (not with Sweave) with both include_graphics and image_read. Avoid the Sweave chunk options and the figure environment using knitr. I would use only include_graphics because image_read cannot work with PDF images and use magic only for load images is rather unnecessary (moreover, I hate packages that print by default a message that you must hide in dynamic reports).

<<loads,echo=F, message=FALSE>>=
A <- "/usr/local/texlive/2019/texmf-dist/tex/latex/mwe/example-image-a.png"
B <- "/usr/local/texlive/2019/texmf-dist/tex/latex/mwe/example-image-b.png"

<<test1,echo=F, fig.align="center", fig.cap="My test1",out.width="50%">>=
x <- 3
if (x >=0 && x <=2){image_read(A)} else if (x>=3 && x<=4){image_read(B)}

<<test2,echo=F, fig.cap="My test2",fig.align='center',out.width="50%">>=
x <- 2
if (x >=0 && x <=2){include_graphics(A)} else 
if (x>=3 && x<=4){include_graphics(B)}

  • Hey Fran! So this solution worked. include_graphics worked with your chunk options, perhaps I was missing something last time. What also worked was library (OpenImageR). I used function readImage to import the images and imageShow to print the images in the output PDF. Thanks!
    – radhika
    Jan 5, 2021 at 14:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .