5

This question is similar, but not identical to this one.

Basically, I have a number of tables that I would like to show in tabsets using DT::datatable(). Unfortunately, I can't figure out how.

The following code works, but I need to manually type all the code:

--- title: "Untitled" format: html --- ```{r} library(DT) ``` ::: {.panel-tabset} ### table no. 1 ```{r} #| results: asis datatable(mtcars) ``` ### table no. 2 ```{r} #| results: asis datatable(mtcars) ``` ::: 

The following works, but instead of datatable() uses a simple markdown table from pander which does not give the desired effect.

--- title: "Untitled" format: html --- ```{r} library(pander) ``` ::: {.panel-tabset} ```{r} #| results: asis for(i in 1:2) { cat(sprintf("\n### table no. %d\n\n", i)) cat(pander(mtcars)) } ``` ::: 

The following code does not work, and I don't know how to make it work:

--- title: "Untitled" format: html --- ```{r} library(DT) ``` ::: {.panel-tabset} ```{r} #| results: asis for(i in 1:2) { cat(sprintf("\n### table no. %d\n\n", i)) print(datatable(mtcars)) } ``` ::: 

1 Answer 1

8

This is a known issue in the context of RMarkdown. But as it turns out the solution for RMarkdown also works for Quarto.

Following this answer related to the same issue in RMarkdown [Discalimer: The answer is from me] you could achieve your desired result by first making sure that the javascript dependencies needed for DT are included in your document and by wrapping the datatable call inside htmltools::tagList:

--- title: "Untitled" format: html --- ```{r} library(DT) ``` ```{r, include=FALSE} # Init Step to make sure that the dependencies are loaded htmltools::tagList(datatable(mtcars)) ``` ::: {.panel-tabset} ```{r} #| results: asis for(i in 1:2) { cat(sprintf("\n### table no. %d\n\n", i)) print(htmltools::tagList(datatable(mtcars))) } ``` ::: 

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Nice! I used to have a weird workaround in Rmarkdown using knitr chunks, but this is so. much. easier.
hey stefan, do you happen to have the equivalent code for different kind of outputs in a tabset? like, datatable, but also gt(), knitr::kable, ggplot, plotly, leaflet.. ? The solution is always a bit different for each output type (sometimes print, sometimes taglist, sometimes print(taglist()) , and it is also different between rmarkdown and quarto.
edit: I ended up being able to do it for most of the packages I use (kable, gt, datatable, ggplot2, ggplotly, mapview, leaflet) and made a quick blog post here simoncoulombe.com/posts/…
Thank you Zoltan - this was very useful! (i particularly enjoyed your comment on initialising the tagList for plot_ly)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.