Reputation: 1363
I recently asked a question about dynamically creating tabsets containing graphs in R markdown.
There are different ways of plotting base R and ggplot graphs. However, it doesn't seem like either the approaches work for DT
tables:
# DataTable Tabs {.tabset .tabset-pills}
```{r}
library(DT)
dt_list <- list(datatable(data.frame('x'=rnorm(100))),
datatable(data.frame('y'=diffinv(rnorm(99)))),
datatable(data.frame('z'=diff(rnorm(101)))))
names(dt_list) <- c('x','y','z')
```
```{r, results='asis'}
for(h in names(df)){
cat("##", h, '<br>', '\n')
cat('This is text for', h, '<br>', '\n\n')
print(dt_list[[h]])
cat('\n', '<br>', '\n\n')
}
```
How would I go about rendering these tabs dynamically? I know DT
tables are built on JS so I imagine the approach would also help with rendering a lot of other types of content dynamically.
Upvotes: 1
Views: 1028
Reputation: 23919
I am not sure where the problem lies. But there is already an issue on GitHub.
A workaround is to render another table and remove it. Also take notice of the use of tagList
within the loop. The datatable library seems to be loaded then and the tabbed datatables work:
---
title: "Untitled"
output: html_document
---
# DataTable Tabs {.tabset .tabset-pills}
```{r}
library(DT)
library(htmltools)
# we simply select the table, look for the parent container
# and remove it from the DOM
jsc <- 'function(settings, json) { $(this).parents(".datatables").remove(); }'
datatable(matrix(NA, 2, 2), options = list("initComplete" = JS(jsc)))
```
```{r}
dt_list <- list(datatable(data.frame('x'=1:10)),
datatable(data.frame('y'=11:20)),
datatable(data.frame('z'=21:30)))
names(dt_list) <- c('x','y','z')
```
```{r, results='asis'}
for(h in names(dt_list)){
cat("##", h, '<br>', '\n')
cat('This is text for', h, '<br>', '\n\n')
print(tagList(dt_list[[h]]))
cat('\n', '<br>', '\n\n')
}
```
Upvotes: 1