R - markdown how to print list of dataframes to "Tabbed sections"

196 Views Asked by At

According bookdown documentation in 3.3, there is functionality to hide chunks in to the tabs. https://bookdown.org/yihui/rmarkdown/html-document.html

I occasionally use it, but I can't figure out how to do it if I print dataframes via loops. Imagine that I have similar dataframe.

df <-
  data.frame(
    id = c(1, 1, 2, 2, 3, 3, 4, 4),
    nr = seq(1, 8)
  )

I split it via id column to following list

t_list <-
  lapply(split(df, df$id), function(df) {

    id <- unique(df$id)

    htmltools::tagList(
      htmltools::h4("TASK"),

      htmltools::tags$table(
        tableHTML::tableHTML(
          login,
          rownames = F)
      )
    )

  })

Expected output is that each id will be in separate tab, but it doesn't work with following code. Please not that I would like to use htmltools in loop part since I enhance tables via javascript.

### TEST

```{r}
htmltools::tagList(t_list)
```
1

There are 1 best solutions below

0
On BEST ANSWER

Here is a way using imap:

---
output: html_document
---

```{r, results='asis', echo=FALSE}

rmd_tabsets <- function(.data) {

  # first empty header to intialize tabsets
  cat("#### { .tabset .unlisted .unnumbered}", "\n\n", sep = "")

  purrr::imap(.data, function(.x, .y) {
    cat("##### TASK ", .y, "\n\n", sep = "")
    print(tableHTML::tableHTML(.x))
    cat("\n\n")
  })
  # close with empty header to stop tabsets
  cat("#### {.unlisted .unnumbered}")
}

df <-
  data.frame(
    id = c(1, 1, 2, 2, 3, 3, 4, 4),
    nr = seq(1, 8)
  )

df_list <- split(df, df$id)

rmd_tabsets(df_list)
```

enter image description here