Thank you, Mike! Here, in case anyone else is interested, is the code I am now using for the MSMB book. It addresses the fact that both x
and options$warning
can be vectors, and cleans up gratuitous formatting inserted by knit
.
cleanup = function(x) gsub("\n#*", "", gsub("^## ", "", x))
knitr::knit_hooks$set(warning = function(x, options) {
ow = options$warning
x = cleanup(unique(x))
keep = if (is.character(ow) && length(ow) > 0) {
res = rep(TRUE, length(x))
for (w in ow)
res = res & !grepl(w, x, ignore.case = TRUE)
res
} else if(is.logical(ow) && length(ow)==1) {
rep(ow, length(x))
} else {
stop("In knit hook for warning, do not know how to handle 'options$warning'.")
}
if (any(keep))
sprintf('<div class="warning"><pre class="knitr %s">%s</pre></div>\n', tolower(options$engine), x[keep])
})
It is then used in code chunks like in the following example.
```{r dbscanfcs, warning = c("stat_contour..: Zero contours were generated", "min.x.: no non-missing arguments to min; returning Inf", "max.x.: no non-missing arguments to max; returning -Inf")}
res5 = dbscan::dbscan(mc5, eps = 0.65, minPts = 30)
mc5df = data.frame(mc5, cluster = as.factor(res5$cluster))
ggplot(mc5df, aes(x = CD4, y = CD8, col = cluster)) + geom_density2d()
```
This approach no longer works following the release of knitr 1.42 and evaluate 0.19. The
warning
chunk option is expecting a logical, and the above approach fortuitously worked; it now breaks following the release of those two packages.We now use a new chunk option
warning.known
to pass the vector of expected warnings. The updated hook is:The following code block will only report the warning "baz" in the output document.
If
warning.known
isn't set, the behaviour is still dictated by the knitr standardwarning
option.