My aim is to add repeated sections to a .docx file, changing values in successive sections by pulling them from a data frame. Using the example code at https://cran.r-project.org/web/packages/officer/vignettes/word.html, I have been able to add a single section, but I have been unable to work out how to make this code work inside a loop.
Here is a minimal example:
library(officer)
library(magrittr)
lastRow <- 10
my_doc <- read_docx() %>%
for(rowNum in 1:lastRow){
body_add_par("ID: ") %>%
if(rowNum < lastRow){
slip_in_text(paste("ID:", rowNum)) %>%
}else{
slip_in_text(paste("ID:", rowNum))
}
print(my_doc, target = "sample.docx")
And here are the error messages I see in my console:
Error: unexpected '}' in:
" slip_in_text(paste("ID:", rowNum)) %>%
}"
> slip_in_text(paste("ID:", rowNum))
Error in x$default_styles : $ operator is invalid for atomic vectors
> }
Error: unexpected '}' in "}"
It seems clear that the problem arises from connecting successive calls to body_add_par with the %>% operator, but I haven't worked out a way around it. Has anyone else encountered a similar problem and worked out a solution?
Thanks.