1

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.

Charles Knell
  • 117
  • 1
  • 9

2 Answers2

2

You can remove the outermost %>% and simply use a combination of assignment and pipe operator in the loop:

library(officer)
library(magrittr)

lastRow <- 10

my_doc <- read_docx() 
for(rowNum in 1:lastRow) {
  my_doc <- my_doc %>% body_add_par("ID: ") %>% slip_in_text(paste("ID:", rowNum))
}

print(my_doc, target = "sample.docx")  
Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
0

It is certainly possible to add paragraphs to a doc using a for loop. It is the only way that I have found to do a bulleted list in Officer. This code works for me to make a list from elements of sector_down_list

if(length(sector_down_list)>0){
    for(this_sector in sector_down_list){
        mydoc<-body_add_par(mydoc,this_sector,style="Bulleted List")
    }
}
jciconsult
  • 31
  • 3
  • I can see how it works with body_add_par(), but what I need is to slip_in_text() within the paragraph, and that won't work in a loop using the %>% operator, but I don't see any other approach to using that operator. Thanks for your interest, and if you have something that works with slip_in_text(), I'll be very happy to have it. – Charles Knell Apr 29 '18 at 02:01