rofficerofficedown

Why is R's officer/officedown moving my header down to the bottom of the page?


I only have one "heading 1" and yet it's at the bottom acting like it's the second header. Is there something I'm not aware of?

enter image description here

Code with example data:

library(flextable)
library(dplyr)
library(officer)
library(officedown)

df <- data.frame(text_level = c(1, 4, 2, 4, 3, 4),
                 text_style = c("heading 1", "Normal", "heading 2", "Normal", "heading 3", "Normal"),
                 text_value = c("Section 1", "Lorem ipsum.", "Section 1.1", "Lorem ipsum.", "Section 1.1.1", "Lorem ipsum."))

doc <- read_docx()
# body_add_par(doc, value = "Hello World!", style = "Normal")
# body_add_par(doc, value = "Salut Bretons!", style = "centered")
for (i in 1:nrow(df)) 
{
  text_value <- as.character(df[i,'text_value'])
  text_style <- as.character(df[i,'text_style'])
  body_add_par(doc, value = text_value, style = text_style)
}
print(doc, target = "example.docx")

Solution

  • The issue is that when adding new paragraphs you have to assign the result back to doc.

    library(officer)
    
    df <- data.frame(
      text_level = c(1, 4, 2, 4, 3, 4),
      text_style = c("heading 1", "Normal", "heading 2", "Normal", "heading 3", "Normal"),
      text_value = c("Section 1", "Lorem ipsum.", "Section 1.1", "Lorem ipsum.", "Section 1.1.1", "Lorem ipsum.")
    )
    
    doc <- read_docx()
    for (i in seq_len(nrow(df)))
    {
      text_value <- df[i, "text_value", drop = TRUE]
      text_style <- df[i, "text_style", drop = TRUE]
      doc <- body_add_par(doc, value = text_value, style = text_style)
    }
    print(doc, target = "example.docx")
    

    enter image description here