Reputation: 1381
I am using the following code to create dynamic tabs with tables in Rmarkdown.
# TEST
``` {r echo=FALSE, results = 'asis', message = FALSE, warnings = FALSE}
print_month <- function(month) {
cat(" \n##", format(month, "%B"), " results \n")
print(knitr::kable(data.frame(A = c(1,2,3), B = c(1,2,3))))
cat(" \n")
}
seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
purrr::walk(print_month)
```
I have seen it working before, but I can't really narrow down why it fails sometimes. When it fails it looks like this
The tables are paragraphs when I look into the HTML code, but when working normally it should be rendered as a table...
Upvotes: 1
Views: 1700
Reputation: 5287
Maybe the print()
and cat()
functions might be interacting with each other?
I prefer functions to return a single assembled string, and let the caller decide how to output it.
library(magrittr)
library(lubridate)
assemble_month <- function(month) {
d <- mtcars[1:5, 1:6] #data.frame(A = c(1,2,3), B = c(1,2,3))
html_table <- knitr::kable(d, format = "html")
paste0(
"\n##", format(month, "%B"), " results\n",
html_table,
"\n"
)
}
seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
purrr::map_chr(assemble_month) %>%
cat()
A disadvantage with my approach though is it outputs the html table in a way fails to leverage knitr's nice markdown-to-html css formatting. I typically add styling back with kableExtra, so html_table
becomes
html_table <- mtcars[1:5, 1:6] %>%
knitr::kable(format = "html") %>%
kableExtra::kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = F
)
(I used a bigger example table to make it look more realistic.)
Upvotes: 2