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 2024). We can add a hook to knitr (Xie 2024)
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
outputfunction. 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:
## # A tibble: 366 × 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
## 4 Canberra 13.3 15.5 39.8 7.2 9.1 NW
## 5 Canberra 7.6 16.1 2.8 5.6 10.6 SSE
## 6 Canberra 6.2 16.9 0 5.8 8.2 SE
## 7 Canberra 6.1 18.2 0.2 4.2 8.4 SE
## 8 Canberra 8.3 17 0 5.6 4.6 E
## 9 Canberra 8.8 19.5 0 4 4.1 S
## 10 Canberra 8.4 22.8 16.2 5.4 7.7 E
## # ℹ 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
———. 2024. 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