From aa11db848d2b736a29f64f79391e5f9d62b38f5b Mon Sep 17 00:00:00 2001 From: Yihui Xie Date: Wed, 10 Apr 2024 11:09:54 -0500 Subject: [PATCH] use options(knitr.kable.max_rows) for kable() to control the maximum number of rows to be generated in the table --- DESCRIPTION | 2 +- NEWS.md | 3 +++ R/table.R | 5 +++++ man/kable.Rd | 3 +++ 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 6bfec03e18..f7f7b4a7dd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: knitr Type: Package Title: A General-Purpose Package for Dynamic Report Generation in R -Version: 1.46.1 +Version: 1.46.2 Authors@R: c( person("Yihui", "Xie", role = c("aut", "cre"), email = "xie@yihui.name", comment = c(ORCID = "0000-0003-0645-5666")), person("Abhraneel", "Sarma", role = "ctb"), diff --git a/NEWS.md b/NEWS.md index e40089fe1f..c5d2eba83e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # CHANGES IN knitr VERSION 1.47 +## NEW FEATURES + +- For `kable()`, you can set the global option `knitr.kable.max_rows` to limit the number of rows to show in the table, e.g., `options(knitr.kable.max_rows = 30)`. This is a way to prevent `kable()` from generating a huge table from a large data object by accident. # CHANGES IN knitr VERSION 1.46 diff --git a/R/table.R b/R/table.R index 820856af66..27f1ef89d5 100644 --- a/R/table.R +++ b/R/table.R @@ -12,6 +12,9 @@ #' default. If you want to display them with other characters, you can set the #' option \code{knitr.kable.NA}, e.g. \code{options(knitr.kable.NA = '')} to #' hide \code{NA} values. +#' +#' You can set the option \code{knitr.kable.max_rows} to limit the number of +#' rows to show in the table, e.g., \code{options(knitr.kable.max_rows = 30)}. #' @param x For \code{kable()}, \code{x} is an R object, which is typically a #' matrix or data frame. For \code{kables()}, a list with each element being a #' returned value from \code{kable()}. @@ -123,6 +126,8 @@ kable = function( caption = kable_caption(label, caption, format) if (!is.matrix(x)) x = as.data.frame(x) + # show the maximum number of rows if set + if (is.numeric(nr <- getOption('knitr.kable.max_rows'))) x = head(x, nr) if (identical(col.names, NA)) col.names = colnames(x) m = ncol(x) # numeric columns diff --git a/man/kable.Rd b/man/kable.Rd index 69520598ea..dfd7fa4d2b 100644 --- a/man/kable.Rd +++ b/man/kable.Rd @@ -84,6 +84,9 @@ Missing values (\code{NA}) in the table are displayed as \code{NA} by default. If you want to display them with other characters, you can set the option \code{knitr.kable.NA}, e.g. \code{options(knitr.kable.NA = '')} to hide \code{NA} values. + +You can set the option \code{knitr.kable.max_rows} to limit the number of +rows to show in the table, e.g., \code{options(knitr.kable.max_rows = 30)}. } \note{ When using \code{kable()} as a \emph{top-level} expression, you do not