firmo23
firmo23

Reputation: 8404

Set image title according to dynamic number of iterations

My script below is supposed to create a word document with as many images as the iterations in the for() loop. In this case I use 2 but the issue is that this number may vary. Also the images' title should be set according to the number of iterations as well. Image1, Image 2 etc. Here instead of 2 images I create 4 and the number of iterations will not be 2 every time.

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

Upvotes: 0

Views: 43

Answers (1)

Dimitrios Panagopoulos
Dimitrios Panagopoulos

Reputation: 147

I am not certain I understand your problem. The code works fine. It just prints four images because you repeat

my_doc <- my_doc %>% 
body_add_img(src = src, width = 5, height = 6, style = "centered") %>% 
body_add_par(paste0("Image",i,"asasa"), style = "Normal")

in your for-loop.

Try the following

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

Upvotes: 1

Related Questions