28.28 Truncating Long Lines

REVIEW The output from knitr (Xie 2023) will sometimes be longer than fits within the limits of the page. We can add a hook to knitr (Xie 2023) so that whenever a line is longer than some parameter, it is truncated and replaced with `...''. The hook extends theoutputfunction. Notice we take a copy of the currentoutput` 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 (out.truncate=NULL):

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=")
## [1] "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=")
## [1] "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 out.truncate=40 included in the knitr options.

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=")
## [1] "This is a very long line that...

References

———. 2023. Knitr: A General-Purpose Package for Dynamic Report Generation in r. https://yihui.org/knitr/.


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0