Reputation: 1165
I am using lists to collect a number of QC plots and tables generated by functions that should be included in a final Rmd markdown html document. The code, as far as I can see, works as expected. All plots and tables are generated and collected. And they are also properly printed in the source window when the whole script is executed.
However, when I knit the document, only the plots are included the way I expect, while the datatables are not. I am not sure why and how to fix this.
Below is a toy example. Apologies for the very long post, but I wanted to show the different behaviors.
Output of individual plot and table in the source window:
library(DT)
plot(cars)
datatable(cars)
Output of plots and tables from lists:
library(DT)
qc_tables <- list()
qc_plots <- list()
qc_plots[[length(qc_plots) + 1]] <- plot(cars)
qc_plots[[length(qc_plots) + 1]] <- plot(iris)
for (p in qc_plots) { print(p) }
qc_tables[[length(qc_tables) + 1]] <- datatable(cars)
qc_tables[[length(qc_tables) + 1]] <- datatable(iris)
for (p in qc_tables) { print(p) }
Screenshot of output in source window:
Now knitting and html output:
---
title: "R Notebook"
output:
html_document
---
# Direct output of plots and Data.Tables
```{r}
library(DT)
plot(cars)
datatable(cars)
plot(iris)
datatable(iris)
```
# Output of plots and Data.Tables from lists
```{r}
library(DT)
qc_tables <- list()
qc_plots <- list()
qc_plots[[length(qc_plots) + 1]] <- plot(cars)
qc_plots[[length(qc_plots) + 1]] <- plot(iris)
for (p in qc_plots) { print(p) }
qc_tables[[length(qc_tables) + 1]] <- datatable(cars)
qc_tables[[length(qc_tables) + 1]] <- datatable(iris)
for (p in qc_tables) { print(p) }
```
Markdown file with direct output:
Markdown output is missing when generating them via a list:
Created on 2021-01-27 by the reprex package (v0.3.0)
Upvotes: 3
Views: 5035
Reputation: 413
I found help here: https://github.com/rstudio/DT/issues/67
this worked for me, it's not a loop, but generated the desired output.
chunk at the top:
library(knitr)
library(DT)
now there are two options, firstly, if your data is in dataframes and you want to format them all the same way:
dflist <- list(iris,cars)
htmltools::tagList(
lapply(dflist, datatable)
)
secondly, if, as pointed out in the comments, you format the datatables ahead of time and have them in a list:
qc_tables <- list()
qc_tables[[length(qc_tables) + 1]] <- datatable(cars)
qc_tables[[length(qc_tables) + 1]] <- datatable(iris)
htmltools::tagList(
lapply(qc_tables, print)
)
Upvotes: 2