Go to TogaWare.com Home Page. Data Science Desktop Survival Guide
by Graham Williams
Duck Duck Go



CLICK HERE TO VISIT THE UPDATED SURVIVAL GUIDE

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 (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 defau...

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...


Support further development by purchasing the PDF version of the book.
Other online resources include the GNU/Linux Desktop Survival Guide.
Books available on Amazon include Data Mining with Rattle and Essentials of Data Science.
Popular open source software includes rattle and wajig.
Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 2000-2020 Togaware Pty Ltd. . Creative Commons ShareAlike V4.