rr-markdownofficedown

Generate tables in a loop with tab.id with officedown R package


Is there a way to generate tables in a loop and set tab.id that can be later cross-referenced? Generating tables in a loop is trivial, but I don't know how to set ids and captions afterwards. Please, see the code below. Here I'm iterating over a list of R data.frames. In the last chunk I put the vector of ids (its lenght is 2) into chunk options - tab.id and tab.cap. This results in generation of two tables (good), but how to get the id of currently processed data.frame in the chunk?

---
output: officedown::rdocx_document  
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r}
library(flextable)

dfs <- list(
  df1 = head(iris),
  df2 = head(mtcars)
)

df_ids <- names(dfs)
```

```{r results='asis', tab.cap=paste("Result for item", df_ids), tab.id=paste0("tab_", df_ids), 
tab.cap.style = "Table Caption"}

flextable(dfs[[???]]) # can current id be accessed somehow?
```

Another option is to use for loop to generate the tables. But how to set tab.id and tab.cap afterwards? Even a workaround solution can be fine for me.


Solution

  • You can probably set these values in a loop by using knitr::opts_chunk$set(). I would probably prefer set_caption in your case.

    To print flextables in a loop inside an R Markdown document, use flextable_to_rmd(). See Looping in R Mardown documents.

    ---
    output: officedown::rdocx_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    ```
    
    ```{r}
    library(flextable)
    library(officer)
    library(officedown)
    library(magrittr)
    
    dfs <- list(
      df1 = head(iris),
      df2 = head(mtcars)
    )
    
    df_ids <- names(dfs)
    ```
    
    ```{r results='asis'}
    for(i in df_ids){
      z <- flextable(dfs[[i]]) %>% 
        set_caption(caption = paste("Result for item", i),
                    style = "Table Caption",
                    autonum = run_autonum(seq_id = "tab", bkm = i))
      flextable_to_rmd(z)
      crossref_id <- sprintf("\\@ref(tab:%s)", i)
      cat("\n\n\nA ref to table ", crossref_id, "\n\n\n\n")
    }
    ```
    
    
    

    enter image description here