6

When using rmarkdown to render pdf document, we can use three options for printing data.frame: default, kable and tibble (see here)

With the default option, it is possible to limit the number of rows printed, with the option: max.print

For tibble, we can use: dplyr.print_max

I can't find a way to limit the number of rows for kable. Is it possible?

divibisan
  • 11,659
  • 11
  • 40
  • 58
John Smith
  • 1,604
  • 4
  • 18
  • 45

3 Answers3

4

kable renders the full data frame passed to it as a table in the output document. AFAIK there's no argument that will limit the number of rows. However, you can preselect the number of rows in the output table (for example, kable(head(dat)) or kable(dat[1:5, ])). If you want to avoid having to select the rows each time, you could write a helper function to limit the number of rows printed. For example:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
```

```{r}
my_kable = function(x, max.rows=6, ...) {
  kable(x[1:max.rows, ], ...)
}
```

```{r}
my_kable(mtcars, caption="My first caption")
```

```{r}
iris$Sepal.Length = 1000 * iris$Sepal.Length
my_kable(iris, 3, caption="My second caption", format.args=list(big.mark=","))
```

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • 1
    thank you eipi10. In fact, I use `df_print: kable` option in `pdf_document:` (knitr header). The idea is to control the max number of rows without altering the code, or the outcome when I run the code (with RStudio). So in my R chunk, I simply put, for example `iris`. The `df_print: kable` option is only used for rendering pdf document. – John Smith Aug 09 '18 at 08:18
  • @XRSC This highlights how important an [mcve] is. Can you provide one? – Ralf Stubner Aug 09 '18 at 10:16
1

A really simple solution is to wrap kable around head:

kable(head(mtcars, n = 5))
broesel23
  • 117
  • 1
  • 9
0

You can create a custom method for printing data frames like this.
Adapted from Yihui Xie's explanation here

---
title: "Untitled"
output: html_document
---

```{r include=FALSE}
knit_print.data.frame <- function(x, ...) {
  head(x, 5) |> 
    knitr::kable() |> 
    paste(collapse = "\n") |>
    knitr::asis_output()
}

registerS3method(
  genname = "knit_print",
  class = "data.frame",
  method = knit_print.data.frame,
  envir = asNamespace("knitr")
)
```

```{r}
iris

tibble::as_tibble(iris)
```
yake84
  • 3,004
  • 2
  • 19
  • 35