In the vignette for the tibble package, there is a possible solution. In your setup chunk of your .Rmd file, put:
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(tibble)
set.seed(1014)
options(crayon.enabled = TRUE)
options(pillar.bold = TRUE, pillar.subtle_num = TRUE)
knitr::opts_chunk$set(collapse = TRUE, comment = pillar::style_subtle("#>"))
colourise_chunk <- function(type) {
function(x, options) {
lines <- x
if (type != "output") {
lines <- crayon::red(lines)
}
paste0(
'<div class="sourceCode"><pre class="sourceCode"><code class="sourceCode">',
paste0(
fansi::sgr_to_html(htmltools::htmlEscape(lines)),
collapse = "\n"
),
"</code></pre></div>"
)
}
}
knitr::knit_hooks$set(
output = colourise_chunk("output"),
message = colourise_chunk("message"),
warning = colourise_chunk("warning"),
error = colourise_chunk("error")
)
In a new chunk:
broom::tidy(stats::chisq.test(table(ggplot2::msleep$vore)))
My HTML output:
