If you are a Word user, it is now possible to automatically update fields and tables of contents instead of having to do it manually from Word, provided you have Word available on the PC hosting R.

According to an issue on github (link) and other requests from users on the subject, the “doconv” package has evolved to answer this.

Let’s take the example of a ‘.docx’ file generated by the following code with package ‘officedown’:

 title: "Exemple with references"
       toc: true
 ```{r setup, include=FALSE}
 knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
 This is `r run_word_field("DOCPROPERTY \"custom_field_value\" \\* MERGEFORMAT")`.
 ## Figure 
 ggplot(iris, mapping = aes(x = Sepal.Length, y = Petal.Length)) +
 ## Table
 flextable(head(iris)) |> autofit()

The document exemple.docx will contain a table of contents and an unset field named custom_field_value.

It is generated by pandoc and the tables of contents, references and in general all the fields calculated by Word are not updated unless the user intervenes manually. The user has to open Word and refresh these fields himself to get for example a table of contents with the right values of titles and corresponding page numbers.

Result with no manual intervention

doconv::docx_update()` will automate this manual process and update the Word document.

x <- read_docx("example.docx")
x <- set_doc_properties(
  custom_field_value = "trop cool"
print(x,target = "updated-example.docx")
docx_update(input = "updated-example.docx")

The previous code set the value “trop cool” to the field named custom_field_value with the function set_doc_properties(). Then the function docx_update() is used to update TOCs and Word computed fields.

The resulting file updated-example.docx looks like this:

Result doconv-update

Follow us:  -  Recommanded sites: R-bloggers R weekly Twitter #rstats Jobs for R-users