Data Science Desktop Survival Guide
by Graham Williams |
|||||
Truncating Long Lines |
Raw The output from knitr
will sometimes be longer than fits within the limits of the page. We
can add a hook to knitr so that whenever a line is
longer than some parameter, it is truncated and replaced with
“...”. The hook 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.truncate=80)
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")) # Truncate each line to length specified. if (!is.null(m <- options$out.truncate)) { len <- nchar(x) x[len>m] <- paste0(substr(x[len>m], 0, m-3), "...") } # Paste lines back together. x <- paste(x, collapse="\n") # Continue with any other output hooks } hook_output(x, options) })
This is useful to avoid ugly looking long lines that extend beyond the
limits of the page. We can illustrate it here by first not truncating
at all ( |
paste("This is a very long line that is truncated",
"at character 80 by default. We change the point", "at which it gets truncated using out.truncate=")
Now we use the default to truncate it.
|
paste("This is a very long line that is truncated",
"at character 80 by default. We change the point", "at which it gets truncated using out.truncate=")
Here is another example, with
|
paste("This is a very long line that is truncated",
"at character 80 by default. We change the point", "at which it gets truncated using out.truncate=")
|