rr-markdownr-flextable

Cannot print crosstab with RMarkdown for a pdf document


I am trying to print a proc_freq table using the flextable package in R Markdown to create a PDF file. Here is the code I used:

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

```{r cars}
sapply(c('am', 'vs'), function(col) print(proc_freq(mtcars, col)))
```

However, when I compile the file, the tables do not appear in the PDF. Can anyone provide any insight into this issue?


Solution

  • print is not a function for knitr rendering.

    The following is a copy of the documentation https://ardata-fr.github.io/flextable-book/rendering.html#looping-in-r-mardown-documents

    Looping in R Mardown documents

    Some codes do not trigger the knitr::knit_print() method. This is the case, for example, of for loop inside a chunk R.

    In this case, you can use knitr::knit_child() that will print the raw code adapted to the output format. Chunk option results must be set to asis.

    When using knitr::knit_child(), the LaTeX and HTML dependencies required to render the content from the included file are automatically detected and integrated into the parent document. This means that if your included file contains elements that require specific LaTeX or HTML packages (this is the case for 'flextable'), knitr::knit_child() will ensure that all these dependencies are properly handled and included in the final document.

    Note the old function flextable_to_rmd() does not directly handle LaTeX and HTML dependencies and should not be used anymore.

    Here is an illustration. We will need two files:

    library(flextable)
    proc_freq(mtcars, col)
    
    ---
    title: blah blah
    output: 
      pdf_document:
        latex_engine: xelatex
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    library(flextable)
    ```
    
    > this is how to print flextables in a loop in a R Markdown document
    
    ```{r results='asis', echo=FALSE}
    sapply(
      c('am', 'vs'),
      function(col) {
        knitr::knit_child(input = "child-loop.Rmd", envir = environment(), quiet = TRUE)
      }) |> 
      cat(sep = '\n')
    ```
    

    enter image description here