Search code examples
r-markdownquarto

How to achieve code reusability in Quarto Markdown (qmd) similar to R Markdown's chunk reusability?


I am attempting to render Quarto markdown (qmd), and in my qmd file, I aim to reuse a code chunk multiple times. Specifically, I wish to execute a code cell with the label label: package-import without displaying its code (i.e. echo: false) for the initial call, but then reuse the code cell to exhibit the commands in a subsequent code cell (i.e. echo: true). This concept is inspired by the implementation of chunk reusability in R Markdown, as elucidated in 14.1 Reuse code chunks | R Markdown Cookbook. However, the means of reusing the code cell described in 14.1.2 Use the same chunk label in another chunk and 14.1.3 Use reference labels (*) are not available when employing qmd. Is there an equivalent feature in qmd that allows for code reusability similar to what is possible in R Markdown?

MWE-same-chunk-label.qmd

To replicate 14.1.2 Use the same chunk label in another chunk using Quarto

```{python}
# | echo: false
# | eval: true
# | label: packcage-import

import os
import session_info
```

```{python}
import session_info

session_info.show()
```

```{python}
# | echo: true
# | eval: false
# | label: packcage-import
```

ERROR: Cell label names must be unique (found duplicate '#packcage-import')

MWE-use-in-another-chunk.qmd

To replicate 14.1.3 Use reference labels (*) using Quarto

```{python}
# | echo: false
# | eval: true
# | label: packcage-import

import os
import session_info
```

```{python}
import session_info

session_info.show()
```

```{python}
# | ref.label="packcage-import"
```

Starting python3 kernel...Done

Executing 'experiment.ipynb'

Cell 1/3...Done

Cell 2/3...Done

Cell 3/3...ERROR:

None of the known patterns match for ref.label="packcage-import"


Solution

  • As Stefan pointed out in the comment, setting engine: knitr in the YAML section of the qmd file is the key solution. Also, it is necessary to install R, rmarkdown, and reticulate for the rendering of the qmd.

    Somehow, the method described in 14.1.2 Use the same chunk label in another chunk only works in my environment.

    ---
    engine: knitr
    ---
    
    ```{python}
    # | echo: false
    # | eval: true
    # | label: packcage-import
    
    import os
    import session_info
    ```
    
    ```{python}
    import session_info
    
    session_info.show()
    ```
    
    ```{python}
    # | echo: true
    # | eval: false
    # | label: packcage-import
    ```