【问题标题】:write docx output after a loop循环后写 docx 输出
【发布时间】:2019-08-19 14:10:42
【问题描述】:

我有一个包含多个患者信息的数据框。我用 R 创建了一个循环来处理每个信息并使用 ReporteRs 将它们写入一个 docx 文件,但是通过这个循环,我获得了与我拥有的主题一样多的 docx,相反,我希望拥有一个一个接一个地包含所有信息的唯一 docx .

这是 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

这是我写的代码

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

因此,通过这种方式,我获得了多个输出,而我想将每个主题的所有行一个接一个地写入一个文档中。 我能做些什么? 谢谢

【问题讨论】:

    标签: r reporters


    【解决方案1】:

    首先,我建议使用同一作者的更新包officer,因为ReporteRs 不再维护。

    对于您的问题:您需要在循环之前创建“docx”对象并在循环之后保存它(最终您还想在循环之前添加标题):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多