Why does datatable not print when looping in rmarkdown?

烈酒焚心 提交于 2019-12-04 11:14:35

This is not a complete answer as some of this is still puzzling me, but at least this is good enough to get you going while I try to understand some more.

---
output: html_document
---

# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```

```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```

```{r include = FALSE}
# Why, oh why do I need this chunk?
datatable(df)
```

```{r results = 'asis'}
for(j in unique(df$classification)){ # You were using level() here, so your for-loop never got off the ground
        df.j <- df[df$classification == j, ]
        cat(paste("\n\n## Classification: ", j, "##\n"))
        print( htmltools::tagList(datatable(df.j)) )
}

The third chunk is required for this to work, I'm not yet sure why.

Reaching here by googling the same question. This has worked for me: https://gist.github.com/ReportMort/9ccb544a337fd1778179.

Basically, generate a list of rendered tibbles and manually call knit.

Here is a working Rmd based on your example, using the technique found in the above link:

---
output: html_document
---

# Setup{.tabset}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(DT)
```

```{r data.setup}
set.seed <- 1242
rows <- 64
data.1 <- runif(rows, 25, 75)
data.2 <- runif(rows, .01, 1)
data.3 <- runif(rows, 1, 10)
classification <- c("A", "B", "C", "D")
df <- data.frame(cbind(data.1 = data.1, data.2 = data.2, data.3 = data.3, classification = classification))
df$data.1 <- as.numeric(df$data.1)
df$data.2 <- as.numeric(df$data.2)
df$data.3 <- as.numeric(df$data.3)
```

```{r include = FALSE}
# prepare a list of 4 sub-dataframes, each corresponding to one classification
df_list <- split(df, df$classification)
```

```{r create-markdown-chunks-dynamically, include=FALSE}

out = NULL
for (c in names(df_list)) {
  knit_expanded <- paste0("\n\n## Classification: ", c, "##\n\n```{r results='asis', echo=FALSE}\n\ndatatable(df_list[['", c, "']])\n\n```")
  out = c(out, knit_expanded)
}

```

<!--- knit those table chunk statements --> 
`r paste(knit(text = out), collapse = '\n')`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!