【问题标题】:adding images to flextable using Display() & as_image() in loop doesnot work在循环中使用 Display() 和 as image() 将图像添加到 flextable 不起作用
【发布时间】:2019-06-30 00:09:54
【问题描述】:

我有一个 zip 文件,其中包含 2 种类型的多个图像。1 -FrequencyRose 图像 2- EnergyRose 图像。我创建了一个 flextable,然后使用 for 循环将偶数行替换为图像,将奇数行替换为图像标题。循环正确显示标题,但它仅多次打印每种类型的最后读取图像,而不是根据循环计数实际打印所有图像。

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


}

这个循环能够正确生成标题,但只有 fr_files[3]、er_files[3] 会循环对应列的所有偶数行。输出为 :final results 。找不到问题。

【问题讨论】:

    标签: r for-loop r-markdown flextable officer


    【解决方案1】:

    我无法重现您的示例(我没有图片)。

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

    从那里你有你需要的一切,灵活的命令可能是:

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

    【讨论】:

    • 感谢大卫的回复。但是当我尝试使用 compose(...as_paragraph()) 而不是 display() 时,它会抛出错误“as_paragraph not found”。
    • 可能你没有最新版本
    猜你喜欢
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多