# Including images in an R code chunk of R sweave using for loop

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:

\begin{figure}
<<echo=FALSE, fig.show='asis', fig=T>>=
library(magick)
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!

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).

\documentclass{article}
\begin{document}
library(magick)
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

• 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! Jan 5, 2021 at 14:10