Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

r - Image not rendering within for loop in rmarkdown

I'm trying to loop through a series of sites and produce a sheet that has text, an image, and a table for each site. I'm using Rmarkdown with PDF output, and am able to get all of the pieces working when I manually select a site and run the code, but can't get the image to show up in the output document when I try to use a for loop.

Following the advice on How to display plot images in Rmarkdown through a for loop? I've tried adding print() to my call to knitr::include_graphics(), and this shows the path to my image followed by [1] “knit_image_paths” “knit_asis”
My path shows up correctly in my output document, and I am using complete absolute paths.

My code:

library(tidyverse) ## for %>%
library(kableExtra)
library(knitr)  

dt = mtcars[1:5,]
car_names = rownames(dt)
dt$Photo = c("a.jpg", "b.jpg", NA, NA, "c.jpg")
photos_folder = "C:/examples"
photos = list.files(photos_folder, pattern = ".jpg")

for(car in car_names){
     writeLines(car)
     writeLines("
Some text goes here 
")
     image  = ifelse(
            is.na(dt$Photo), "No Photo",
            photos[str_detect(photos, dt$Photo)]
      )

      if(is.na(row$Photo)) writeLines(image)
         
      if(!is.na(row$Photo)) include_graphics(file.path(photos_folder, image)) %>% 
           print()

  dt %>% 
       select(mpg, qsec, carb) %>%
       kbl() %>%
       print()
     
}

If I set car = car_names[1], comment out the for loop, and take out the call to print() for the image everything shows up correctly. With the for loop, nothing shows up where the image should be unless I add the call to print() back in, but in this case I get the path and the options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...