Hi there,
I performed a reprex with your problem and it works.
See screenshot:
See code:
title: "Hack the output with hooks"
knitr::opts_hooks$set(rm.last = function(options) {
options$code <-
paste0(
options$code,
c(rep("", length(options$code) - options$rm.last),
rep(" # REMOVE", options$rm.last)
)
)
options
})
builtin_source_hook <- knitr::knit_hooks$get('source')
knitr::knit_hooks$set(source = function(x, options) {
if (!is.null(options$rm.last))
x <- grep("# REMOVE$", x, invert = TRUE, value = TRUE)
if (length(x) > 0) {
return(builtin_source_hook(x, options))
} else {
invisible(NULL)
}
})
a <- 1
b <- 2
x <- a + b
print(paste(c("`x` is equal to ", x), collapse=""))
library(tidyverse)
output <-
mtcars %>%
filter(mpg >= 21) %>%
arrange(mpg) %>%
head() %>%
knitr::kable()
output
As you will see we only have library(tidyverse) loading while the last 5 lines got disabled via rm.last=5.