Data Science Desktop Survival Guide
by Graham Williams |
|||||
Truncating Too Many Lines |
Raw Another issue we sometimes want to deal
with is limiting the number of lines of output displayed from
knitr. We can add a hook to knitr
so that whenever we have reached a particular line count for the
output of any command, we replace all the remaining lines with
“...”. The hook again extends the output
function. Notice
we take a copy of the current output
hook and then run that
after our own processing.
opts_chunk$set(out.lines=4)
hook_output <- knit_hooks$get("output") knit_hooks$set(output=function(x, options) { if (options$results != "asis") { # Split string into separate lines. x <- unlist(stringr::str_split(x, "\n")) # Trim to the number of lines specified. if (!is.null(n <- options$out.lines)) { if (length(x) > n) { # Truncate the output. x <- c(head(x, n), "....\n") } } # Paste lines back together. x <- paste(x, collapse="\n") } hook_output(x, options) })
We can then illustrate it: |
weather[2:8]
Now we set
|
weather[2:8]
|