Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way to initialize JS renderer in 'asis' R Markdown chunk

'asis' chunks are very useful to output a list of objects in a Markdown document, see following examples : Highcharter, DT, Leaflet, ...

However, in the above examples, the list of object won't print if the renderer hasn't been called once in a previous chunk, so that it gets initialized : this is a tricky workaround, and I found the solution more by trial / error than by finding it in documentation.

This is a reproducible issue also posted on https://github.com/rstudio/rmarkdown/issues/1877 :

---
title: "Test"
output:
  html_document
---



```{r,echo=F}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)

df_list <- list("cars" = mtcars, "flowers" = iris)

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
```

```{r}
# If this first initialization isn't run, tabs won't print
DT::datatable(data.frame())
```

# Test tabs {.tabset}

```{r, results='asis' }
imap(df_list, ~{
  cat('## Subtab ',.y,'\n')
  cat('\n')
  DT::datatable(.x) %>%
    htmltools::tagList() %>% as.character() %>% cat() })

```
 

  
like image 429
Waldi Avatar asked Dec 30 '22 22:12

Waldi


1 Answers

You can output multiple datatables without asis. Just put the list of widgets into tagList()

```{r}
library(purrr)
list("cars" = mtcars, "flowers" = iris) %>%
  map(~DT::datatable(.x)) %>%
  htmltools::tagList()
```
like image 82
atusy Avatar answered Jan 31 '23 10:01

atusy