根据动态迭代次数设置图像标题

时间:2019-03-14 13:26:31

标签: r

我下面的脚本应该创建一个Word文档,其中包含与for()循环中的迭代一样多的图像。在这种情况下,我使用2,但问题是此数字可能有所不同。同样,图像标题也应根据迭代次数设置。 Image1,Image 2等。这里我创建2个图像,而不是2个图像,并且每次迭代的次数都不会是2。

library(officer)
library(magrittr)
library(flextable)

src <- tempfile(fileext = ".png")
png(filename = src, width = 5, height = 6, units = 'in', res = 300)
barplot(1:10, col = 1:10)

dev.off()


current_dir <- getwd()

my_doc <- read_docx()


#Baseline Summary Stats Table
for(i in 1:2){
  my_doc <- my_doc %>% 
    body_add_img(src = src, width = 5, height = 6, style = "centered") %>% 
    body_add_par(paste0("Image",i,"asasa"), style = "Normal")


#Baseline Summary Stats Table

my_doc <- my_doc %>% 
  body_add_img(src = src, width = 5, height = 6, style = "centered") %>% 
  body_add_par(paste0("Image",i,"asasa"), style = "Normal")
}
#writing to word file
print(my_doc, target = "first_example.docx")

1 个答案:

答案 0 :(得分:1)

我不确定我了解您的问题。该代码工作正常。因为重复

,它仅打印四张图像
my_doc <- my_doc %>% 
body_add_img(src = src, width = 5, height = 6, style = "centered") %>% 
body_add_par(paste0("Image",i,"asasa"), style = "Normal")

在您的循环中。

尝试以下

library(officer)
library(magrittr)
library(flextable)

src <- tempfile(fileext = ".png")
png(filename = src, width = 5, height = 6, units = 'in', res = 300)
barplot(1:10, col = 1:10)

dev.off()


current_dir <- getwd()

my_doc <- read_docx()


# set number of iterations
n=3

#Baseline Summary Stats Table
for(i in 1:n){
  my_doc <- my_doc %>% 
    body_add_img(src = src, width = 5, height = 6, style = "centered") %>% 
    body_add_par(paste0("Image",i,"asasa"), style = "Normal")


}
#writing to word file
print(my_doc, target = "first_example.docx")