Issue
edit
This issue is not (necessarily) only related to {htmlTable}. The same happens when rendering a html table which has been styled with the {kableExtra} package (see also this thread).
original question
I'm working in RMarkdown, trying to render a document with htmltables
from the htmlTable package in a loop. When I push the "Knit" button in RStudio, everything works great. But when I use the render()
function, the htmltables
in the loop don't get printed, but the table just before the loop does.
I read that "knit" button and the render function does the same, so I don't understand whats wrong?
This is a working example of a .Rmd
file with a hmtlTables
:
---
output: html_document
---
## htmlTables
```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
cat( paste('## title no.', i, '\n' ) )
print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
print(htmlTable(a*i))
cat('\n')
}
```
I need to generate many reports automatically with different parameters, so I need to get this working with render()
.
Solution
htmlTable has defined a print
method, which appears to print the table in a new window, change print()
to writeLines()
will do the trick:
---
output: html_document
---
## htmlTables
```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
cat( paste('## title no.', i, '\n' ) )
print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
writeLines(htmlTable(a*i))
cat('\n')
}
```
However it still seems a bit strange to me because I believe that the knit button uses rmarkdown::render() under the hood but they have different behaviors in this case.
Answered By - TC Zhang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.