28.29 Truncating Too Many Lines
REVIEW Another issue we sometimes want to deal
with is limiting the number of lines of output displayed from
knitr (Xie 2025). We can add a hook to knitr (Xie 2025)
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 theoutputfunction. Notice we take a copy of the currentoutput` 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:
## # A tibble: 366 × 7
## Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <ord>
## 1 Canberra 5 13.9 0 NA NA NNW
## 2 Canberra -4.1 15.7 0 NA NA SSW
## 3 Canberra -3.3 13.4 0.2 NA NA SE
## 4 Canberra 3 12 0 NA NA N
## 5 Canberra 7.4 15 2.8 NA NA NW
## 6 Canberra -0.6 12.4 0.2 NA NA N
## 7 Canberra 2.5 11.8 0.2 NA NA NW
## 8 Canberra 5.6 9.9 0 NA NA NW
## 9 Canberra 6.2 11.8 4.4 NA NA NW
## 10 Canberra 6.5 12.2 0 NA NA WNW
## # ℹ 356 more rows
Now we set out.lines=2 to only include the first two lines.
## # A tibble: 366 × 7
## Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir
....
References
———. 2025. Knitr: A General-Purpose Package for Dynamic Report Generation in r. https://yihui.org/knitr/.
If you find this curated material useful then you can consider a donation to support it's ongoing availability and give you access to the PDF version of this book. The material has been scoped up by Generative AI without permission or any kind of recompense so do consider a donation if you can afford it. Unlike Generative AI your access to this materials is freely given. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Togaware has a 30 year tradition of making popular open source software which includes sold privacy preserving productivity apps, 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