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 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]
## # A tibble: 366 x 7
##    Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir
##    <chr>      <dbl>   <dbl>    <dbl>       <dbl>    <dbl> <ord>      
##  1 Canberra     5      24.3      0           3.4      6.3 NW         
##  2 Canberra    14      26.9      3.6         4.4      9.7 ENE        
##  3 Canberra    13.7    23.4      3.6         5.8      3.3 NW         
....

Now we set out.lines=2 to only include the first two lines.

weather[2:8]
## # A tibble: 366 x 7
##    Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir
....


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.