rquarto

How do I print only n lines of code output in a Quarto document?


This works but I would like something more user friendly. Is there not a chunk option that sets the R code output to be a certain number of lines?

---
title: "Glimpse Output Example"
format: html
---

```{r}
# Load required package
library(dplyr)

# Create the data frame
set.seed(123)
df <- as.data.frame(matrix(rnorm(10000 * 150), nrow = 10000, ncol = 150))
colnames(df) <- paste0("Var", 1:150)

# Capture glimpse output
glimpse_output <- capture.output(glimpse(df))

# Show only the first 10 lines
cat(paste(glimpse_output[1:10], collapse = "\n"))
))
```

This works in the context of an RMarkdown document, but I cannot get it to work in a Quarto document. How would I convert this?

---
title: "Untitled"
output: html_document
date: "2025-09-25"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  lines <- options$output.lines
  if (is.null(lines)) {
    return(hook_output(x, options))  # pass to default hook
  }
  x <- unlist(strsplit(x, "\n"))
  more <- "..."
  if (length(lines)==1) {        # first n lines
    if (length(x) > lines) {
      # truncate the output, but add ....
      x <- c(head(x, lines), more)
    }
  } else {
    x <- c(more, x[lines], more)
  }
  # paste these lines together
  x <- paste(c(x, ""), collapse = "\n")
  hook_output(x, options)
})
library(tidyverse)
glimpse(mtcars)

Solution

  • Here is how you can write a knitr output hook in a Quarto document.

    ```{r setup, include=FALSE}
    hook_output <- knitr::knit_hooks$get("output")
    knitr::knit_hooks$set(output = function(x, options) {
        n <- options$output.lines
        if (is.null(n)) return(hook_output(x, options))
        lines <- unlist(strsplit(x, "\n", fixed = TRUE))
        if (length(lines) > n) {
            x <- paste(
                c(
                    lines[seq_len(n)],
                    sprintf("<snipped %s lines>", length(lines) - n)
                ),
                collapse = "\n"
            )
        }
        hook_output(x, options)
    })
    ```
    

    Note that we define options$output.lines, and then pass it as an option in each chunk using the #| output.lines: 10 format. For example, if the rest of your Quarto document looks like this:

    ```{r}
    #| output.lines: 10
    mtcars
    ```
    
    ```{r}
    #| output.lines: 5
    #| message: false
    library(dplyr)
    set.seed(123)
    df <- as.data.frame(matrix(rnorm(10000 * 150), nrow = 10000, ncol = 150))
    colnames(df) <- paste0("Var", 1:150)
    glimpse(df)
    ```
    

    You'll get this:

    enter image description here