简体   繁体   中英

write docx output after a loop

I have a data frame with several information about patients. I created a loop with R to process each information and write them to a docx file using ReporteRs, but with this loop I obtain as much docx as subjects I have, instead I would like to have 1 unique docx with all information one after the other.

this is the df

Surname Name    Born    Subject Place
Halls   Ben 09/08/2019  3387502 S.Jeorge
Beck    David   12/08/2019  1319735 S.Jeorge
Essimy  Daniel  12/08/2019  3387789 S.Jeorge
Rich    Maria   12/08/2019  3307988 S.Agatha

and this is the code I have written

dfY2 <- read.table("file.txt",header=T)

for(i in 1:nrow(dfY2)) {
my_title <- pot('Exam', textProperties(font.weight = "bold",font.size=12, font.family="Times New Roman"))    
row1<-pot("Surname and Name",textProperties(font.weight="bold"))+" "+pot(dfY2[i,1])+" "+pot(dfY2[i,2])+" "+pot("Born",textProperties(font.weight="bold"))+pot(dfY2[i,3])
row2<-pot("SubjectID",textProperties(font.weight="bold"))+" "+pot(dfY2[i,4])+pot("Place",textProperties(font.weight="bold"))+" "+pot(dfY2[i,5])

doc<-docx("Template.docx")%>%
   addParagraph(my_title, par.properties=parProperties( text.align = "center"))%>%
   addParagraph(c(""))%>%
   addParagraph(row1)%>%
   addParagraph(row2)%>%
writeDoc(doc,file = paste0(dfY2[i,1],"output.docx"))
}

So, in this way, I obtain several outputs, while I would like to write all the rows one after the other for each subject in only a single doc. What can I do? thanks

First of all, I would recommend using the newer package officer from the same author because ReporteRs is not anymore maintained.

To your question: you need to create the 'docx' object before the loop and save it after the loop (eventually you want to add the title before the loop as well):

doc <- docx("Template.docx")

for(i in 1:nrow(dfY2)) {
  ...

  doc <- doc %>%
    addParagraph(my_title, par.properties=parProperties( text.align = "center")) %>%
    addParagraph(c("")) %>%
    addParagraph(row1) %>%
    addParagraph(row2)

}

writeDoc(doc, file ="output.docx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM