Create code chunks

Creating a Chunk

Quarto documents in RStudio can be edited in two modes. In Visual mode, you insert a chunk via Insert → Executable Cell → [language].

Creating chunks through the Visual mode

In Source mode, you create a chunk by typing three backticks followed by the language in curly braces (e.g., ```{r}) and closing it with another three backticks; everything between the fences is executable code.

Creating chunks through the Source mode

Visual mode is a convenient way to build a document with a guided interface, but we recommend working in Source mode as much as possible once you’re comfortable with the syntax.

Rendering Regularly

Because chunks share one session and run top to bottom, it’s good practice to render your document often as you write it, rather than waiting until the end.

Predict: suppose you write five chunks in a row without rendering, and the second chunk has an error. What do you expect to happen when you finally render the whole document?

Explain: rendering stops at the first chunk that fails, and Quarto reports an error pointing to that chunk. This means that you would not learn about the problem until you’d already written three chunks past it, making it harder to pinpoint what went wrong. Rendering after every chunk or two (with the Render button, Ctrl/Cmd+Shift+K, or quarto render yourfile.qmd) catches this immediately instead. You can also run a single chunk on its own with the green play icon (or Ctrl/Cmd+Shift+Enter) to test it before rendering the full document.

Labelling Chunks

Each chunk can be given a label, specified with #| label: <name> immediately inside the chunk. Labels make errors easier to trace back to their source, and are used internally for caching and for naming generated figures and tables. Good labels are unique, short but descriptive, and use only lowercase letters, numbers, and hyphens or underscores, for example data-load, model-fit, or plot-results.

Common Mistake

Chunk labels must be unique within a document. If two chunks share the same label, Quarto will fail to render and report a duplicate-label error. This is easy to run into if you copy-paste an existing chunk as a starting point for a new one and forget to change its label.

Practice Exercise

Which of the following chunk labels follows good labeling convention: Model Fit!, model_fit_final_version_2, or model-fit?

model-fit. It is short, descriptive, unique, and uses only lowercase letters and a hyphen. Model Fit! uses spaces, capital letters, and a special character, none of which are recommended, and model_fit_final_version_2 is unnecessarily long for a label.

Back to top