'quarto rmarkdown code block to only display certain lines

I have a .qmd / .rmd file that wants to show the output of block of code. The code block has a lot of lines at the beginning that I'd like to hide, in the example below I'd like the output to be the third line of code str(month) and output the result of str(month). I've attempted to edit the code block parameters, but it's giving me an error:

---
format:
  html: default
---

```{r}
#| echo: c(3)
month <- "July"

str(month)
```

Error:

7: #| echo: c(3)
            ~~~
8: month <- "July"
x The value c(3) is string.
i The error happened in location echo.

rmarkdown support files suggest something like this might be possible



Solution 1:[1]

This does not work because you are using YAML syntax for chunk options as recommended with Quarto but #| echo: c(3) is not valid YAML. #| echo: 3 is.

You can use !expr within YAML field to parse R code if necessary. #| echo: !expr c(3) would work. It is explained here: https://quarto.org/docs/computations/r.html#chunk-options

However, know that knitr supports other way to specify chunk options:

  • Usual header where option needs to be valid R code
```{r, echo = c(3)}
#| echo: c(3)
month <- "July"

str(month)
```
  • And a multiline version of it, useful when having long option like fig.cap
```{r}
#| rmdworkflow,
#| echo = FALSE,
#| fig.cap = "A diagram illustrating how an R Markdown document
#|   is converted to the final output document.",
#| out.width = "100%"

knitr::include_graphics("images/workflow.png", dpi = NA)
```

See the announced in blog post for more about this new syntax: https://yihui.org/en/2022/01/knitr-news/

This question has also been asked in Github - so more detailed answer there: https://github.com/quarto-dev/quarto-cli/issues/863

Solution 2:[2]

I don't know if I understood the question correctly. But you can choose to display only the code you want based on the index of the line inside specific chunk. Insert the number of index line you want to show inside the c() {r, echo = c()}

Your specific case

---
format:
  html: default
---

```{r, echo = c(2)}
month <- "July"
str(month) # line 2
```

Other Example:

---
format:
  html: default
---

```{r, echo = c(5,8)}
# Hide
month <- "July"

## Show code and output
str(month) # Line 5

## Show code and output
1+1 # Line 8

## Show just output
2+2

```

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cderv
Solution 2