1

In R markdown, I want to output a sortable table while the r chunk is set to results='asis'

DT::datatable yields the desired kind of output that I'm looking for. However that doesn't seem work with results='asis' set. I'm not sure if there's any kind of escape to this setting.


```{r setup, include=FALSE}
library(knitr)

my_data = mtcars

df_list = list()

df_list[[1]] = my_data[1:5,]
df_list[[2]] = my_data[6:10,]
### tabs {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(df_list)){
  cat("#### tab", i)
  print(kable(df_list[[i]]))
  cat('\n\n')
}

(*In the code above I had to omit the closing of r chunks "```" because I couldn't figure out how to properly display that in here)

As you can see, the second r chunk has results='asis' set. I'm setting it because I want to dynamically generate the tabs within the for loop. I'm printing the tables using print(kable...) but they are not sortable. Is there a way to output sortable tables once I have the file knitted? Thanks!

Waldi
  • 39,242
  • 6
  • 30
  • 78
ralphxiaoz
  • 101
  • 1
  • 6

1 Answers1

0

The DT renderer has to be initialized, as shown here and discussed more generally here:

---
title: "DT tabs"
output: html_document
---


```{r setup, include=FALSE}
library(knitr)
library(dplyr)
library(DT)

my_data = mtcars

df_list = list()

df_list[[1]] = my_data[1:5,]
df_list[[2]] = my_data[6:10,]
data.frame() %>%
  DT::datatable() %>%
  knitr::knit_print() %>%
  attr('knit_meta') %>%
  knitr::knit_meta_add() %>%
  invisible()


```

### tabs {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(df_list)){
  cat("#### tab", i,'\n')
  print(htmltools::tagList(DT::datatable(df_list[[i]])))
  cat('\n\n')
}

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78