TransWikia.com

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

TeX - LaTeX Asked on April 22, 2021

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

One Answer

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}
<<loads,echo=F, message=FALSE>>=
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
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)}
@

end{document}

Correct answer by Fran on April 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP