htmlrknitrquarto

Quarto knitr output to HTML merges tables


I am using kables() to output multiple tables from one function in R in a Quarto document rendered with knitr. This works, but the layout is basically merged like one large combined table.

Here is a minimal Quarto markdown file (.qmd)

    ---
    title: "Example"
    date: '28 February 2024'
    toc: true
    number-sections: true
    format: 
      html: 
        code-fold: true
    ---

    # Example

    ```{r}
    library(knitr)

    f <- function() {
    kables(
      list(
        kable(head(iris), caption = "a"),
        "<br><br>",
        kable(tail(iris), caption = "b")))
    }
    ```

    Make the tables.

    ```{r}
    f()
    ```

and I got this: enter image description here

What I am hoping to achieve is the same output but rather than being merged to the right, the tables are put down below with a line break. I tried adding breaks in html as part of output but that does not seem to help.

Alternately if there is a better way to write a function in R that would output multiple tables, that would also be fine.


Solution

  • I would use purrr::walk2 for that:

    ---
    title: "Example"
    date: '28 February 2024'
    toc: true
    number-sections: true
    format: 
      html: 
        code-fold: true
    ---
    
    # Example
    
    ```{r}
    library(knitr)
    library(purrr)
    ```
    
    Make the tables.
    
    ```{r}
    #| results: asis
    walk2(
      list(head(iris), tail(iris)), c("a", "b"), ~kable(.x, caption = .y)|> print()
    ) 
    ```
    

    enter image description here