Karthik Nani
Karthik Nani

Reputation: 23

adding images to flextable using Display() & as_image() in loop doesnot work

I have a zip file which has multiple images of 2 types.1 -FrequencyRose images 2- EnergyRose images. I have created a flextable and then replacing the even rows with images and odd rows with the image titles using for loop . The loop is correctly displaying the titles but its only printing the last read image of each type mulitple times instead of actually printing all the images as per loop count.

img.file <- unzip("D:\\Mast_Image Files.zip")
fr_files <- img.file[grepl(paste("FrequencyRose", collapse = "|"), img.file)]
er_files <- img.file[grepl(paste("EnergyRose", collapse = "|"), img.file)]

fr_files has 3 image file paths and same with er_files click

num_masts = length(img.file)

c1 = rep("Freq_rose",num_masts)
c2 = rep("Energy_Rose",num_masts)

df = data.frame(c1,c2)


dfft = flextable(df)

sso=seq(1,num_masts,2)
sse=seq(2,num_masts,2)

for (g in 1:(num_masts/2)){

  ff.img = fr_files[g]
  ef.img = er_files[g]

  dfft2 = dfft %>%
    display(
      i = sse[g], col_key = "c1", pattern = "{{img}}",
      formatters = list( img ~ as_image(c1,
                                        src = ff.img, width = 3, height = 3))) %>%

    display(
      i = sse[g], col_key = "c2", pattern = "{{img}}",
      formatters = list( img ~ as_image(c2,
                                        src = ef.img, width = 3, height = 3))) %>%

    display(
      i = sso[g], col_key = "c1", pattern = paste("Freq_Rose","mast",g)) %>%

    display(
      i = sso[g], col_key = "c2", pattern = paste("Energy Rose","mast",g))


}

this loop is able to produce titles correctly but the only the fr_files[3], er_files[3] is looping over all the even rows of corresponding columns. output is as :final results . could not find the issue.

Upvotes: 1

Views: 873

Answers (1)

David Gohel
David Gohel

Reputation: 10675

I can't reproduce your example (I don't have the images).

library(ggplot2)
library(tidyverse)
library(flextable)

# a data example ----
zz <- iris %>% 
  group_by(Species) %>% 
  summarise( n = n(), avg = mean(Petal.Length), 
             img_path = paste0( unique(as.character(Species)), ".png"),
             gg = list(ggplot(tibble(Sepal.Length, Petal.Width), aes(Sepal.Length, Petal.Width)) + geom_point() + theme_minimal())
             )
zz
# create the png ----
walk2(zz$gg, zz$img_path, function(gg, path){
  png(filename = path, width = 300, height = 300)
  print(gg)
  dev.off()
})

From there you have everything you need and the flextable commands could be:

# create the flextable -----
flextable(zz, col_keys = c("Species", "n", "avg", "plot")) %>% 
  # here, i is selecting only odd rows 
  compose(i = ~ seq_along(Species) %% 2 > 0, j = "plot", value = as_paragraph(as_image(img_path, width = 300/72, height = 300/72))) %>% 
  theme_box() %>% 
  autofit()

enter image description here

Upvotes: 1

Related Questions