rr-markdownofficerofficedowncrosstable

Cross-referencing tables {SEQ Table \\* arabic} and figures {SEQ Figure \\* arabic} with officedown [i.e. block_caption() and run_autonum()]


I want to create a .docx report with {officedown}, but instead of using "bookmark" reference types for cross-referencing my tables and figures as suggested in ch.4.6 and ch.4.7 of the User Documentation, I would like my references to be actual "Figure" and "Table" reference types in the resulting .docx. As discussed in this stackoverflow post, this would require {SEQ Figure \\* arabic} and {SEQ Table \\* arabic} word fields and the answers show how to implement this via officer::slip_in_seqfield() or crosstable::body_add_table_legend().

However, I think, these approaches to obtain actual "Figure" and "Table" reference types only work for the {officer} syntax and not the {officedown} syntax. To be clear, so far I understood

(please correct me if I am wrong)

Therefore, I would like to know whether there is a way to modify the suggested approach in {officedown} in order to obtain actual "Figure" and "Table" reference types that I can also cross-reference in the text. Below is an example using the standard suggested approach:

You can also make use of the `run_autonum()` and `block_caption()` functions 
of the {officer} package. Here are the cross references to Table \@ref(tab:tabmtcars2) 
and Figure \@ref(fig:figmtcars2). This approach can be used for tables and figures 
and the corresponding reference type in MS Word will always be "bookmark".

```{r}
# Table
run_autonum(seq_id = "tab",
            bkm = "tabmtcars2") %>%
  block_caption(autonum = .,
                label = "mtcars table",
                style = "Table Caption")

head(mtcars)

# Figure
ggplot(head(mtcars), aes(x = mpg, y = hp)) + 
  geom_point() + theme_bw()

run_autonum(seq_id = "fig",
            bkm = "figmtcars2") %>%
  block_caption(autonum = .,
                label = "mtcars figure",
                style = "Image Caption")
```

enter image description here


Solution

  • This is my first time posting here, so sorry if I get formatting/etc. incorrect. But if I understand you correctly, officer::run_reference may be what you are looking for. Thomas de Marchin gives a really helpful example of this here.

    The essence of this is to use block_caption with officer::run_autonum in your r code block, and then use officer::run_reference in the markdown in the place of \@ref(tab:some-tab) as follows:

    ```{r}
    block_caption(label = 'The Caption',
                  style = 'Table Caption',
                  autonum = officer::run_autonum(seq_id = 'tab', bkm = 'some-tab'))
    
    head(mtcars) %>% flextable()
    ```
     This is a reference to Table `r officer::run_reference('some-tab')`