簡體   English   中英

在循環中使用Display()和as_image()將圖像添加到flextable不起作用

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

我有一個zip文件,其中包含2種類型的多個圖像。1-FrequencyRose圖像2-EnergyRose圖像。 我創建了一個彈性表,然后使用for loop將帶有圖像的偶數行和帶有圖像標題的奇數行替換。 該循環正確顯示了標題,但是它僅多次打印每種類型的最后讀取圖像,而不是根據循環計數實際打印所有圖像。

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具有3個圖像文件路徑,與er_files相同, 請單擊

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


}

此循環能夠正確產生標題,但是只有fr_files [3],er_files [3]循環遍歷相應列的所有偶數行。 輸出為: 最終結果 找不到問題。

我無法復制您的示例(我沒有圖像)。

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()
})

從那里您擁有所需的一切,而flextable命令可以是:

# 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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM