rofficer

How can I add elements to an existing officer block_list object?


I have an existing officer block_list object and would like to extend it after its original creation. How can I achieve that?

i.e. in the code below, how can I create my_block_list_2 with a preexisting my_block_list_1?

library(officer) # 0.6.2

my_block_list_1 <- block_list(fpar("Something on the left",
                                   fp_p = fp_par(text.align = "left")))

my_block_list_2 <- block_list(fpar("Something on the left",
                                   fp_p = fp_par(text.align = "left")),
                              fpar("Something on the right",
                                   fp_p = fp_par(text.align = "right")))

Solution

  • Since the block_list is a list (can be checked with is.list()) we can simply add the additional element to position two of that list. When comparing my_block_list_1 with my_block_list_2 via all.equal() after the addition we find that they are indeed the same.

    library(officer) # 0.6.2
    
    my_block_list_1 <- block_list(fpar("Something on the left",
                                       fp_p = fp_par(text.align = "left")))
    
    my_block_list_2 <- block_list(fpar("Something on the left",
                                       fp_p = fp_par(text.align = "left")),
                                  fpar("Something on the right",
                                       fp_p = fp_par(text.align = "right")))
    
    
    my_block_list_1[[2]] <- fpar("Something on the right",
                                 fp_p = fp_par(text.align = "right"))
    
    all.equal(my_block_list_1, my_block_list_2)
    

    In the context of an actual Rmd we also see that it works when rendering:

    ---
    output:
      officedown::rdocx_document:
        base_format: "rmarkdown::word_document"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(officedown) # 0.3.3
    library(officer) # 0.6.2
    library(ggplot2) # 3.4.2
    library(flextable) # 0.9.4
    ```
    
    ```{r}
    my_block_list_1 <- block_list(fpar("Something on the left",
                                       fp_p = fp_par(text.align = "left")))
    
    my_block_list_1[[2]] <- fpar("Something on the right",
                                 fp_p = fp_par(text.align = "right"))
    
    block_section(prop_section(footer_default = my_block_list_1))
    ```
    
    ```{r my-figure, fig.cap = "A figure."}
    ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point()
    ```