Understanding Code Chunks

Session - Code Chunks

Zoë Turner

Adding and running code chunks

  1. Add a code chunk with Green square button with white c found in RStudio to create a new chunk button
  2. Keyboard shortcut keys Ctrl + Alt + i
  3. In Visual screen of RStudio type /

Running a chunk

  1. Play an individual chunk with the green triangle
  2. Render button to run all chunks and produce the output
  3. Shortcut key to run a chunk Ctrl + Shift + Enter

Default Code chunk settings

```{r}
NHSRdatasets::covid19 |>
  filter(countries_and_territories == "United_Kingdom") |>
  summarise(total = n())
```

Let’s see the fate of this chunk…

# A tibble: 1 × 1
  total
  <int>
1   350

Tibble?

This is a view of the data that would normally go to the Console when run as a chunk so includes information like data types (A tibble:...).

Object creating Code chunk

```{r}
uk_data <- NHSRdatasets::covid19 |>
  filter(countries_and_territories == "United_Kingdom") |>
  summarise(total = n())
```

What happens here if we create an object?

Nothing shows!

With echo: false there is no code and even with eval: true it has run but there is no output to see - why?

Showing results

```{r}
#| code-line-numbers: "7"
uk_data <- NHSRdatasets::covid19 |>
  filter(countries_and_territories == "United_Kingdom") |>
  summarise(total = n())

uk_data
```

Can we now see the results?

# A tibble: 1 × 1
  total
  <int>
1   350

Metadata is still showing!

The information about the table is still showing (A tibble:... )

Using packages for tables

Tables are the output of data (not data frames which are data object types)

library(gt)

gt(NHSRdatasets::covid19 |> head(5))
date_reported continent countries_and_territories country_territory_code population_2019 cases deaths
2020-12-14 Asia Afghanistan AFG 38041757 746 6
2020-12-13 Asia Afghanistan AFG 38041757 298 9
2020-12-12 Asia Afghanistan AFG 38041757 113 11
2020-12-11 Asia Afghanistan AFG 38041757 63 10
2020-12-10 Asia Afghanistan AFG 38041757 202 16

Controlling output

```{r}
glimpse(NHSRdatasets::covid19)
```

Default option

When nothing is set all options are true.

Code, messages, warnings are shown and the code is “evaluated” (it breaks if there is a bug).

glimpse(NHSRdatasets::covid19)
Rows: 61,900
Columns: 7
$ date_reported             <date> 2020-12-14, 2020-12-13, 2020-12-12, 2020-12…
$ continent                 <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, As…
$ countries_and_territories <fct> "Afghanistan", "Afghanistan", "Afghanistan",…
$ country_territory_code    <fct> AFG, AFG, AFG, AFG, AFG, AFG, AFG, AFG, AFG,…
$ population_2019           <int> 38041757, 38041757, 38041757, 38041757, 3804…
$ cases                     <int> 746, 298, 113, 63, 202, 135, 200, 210, 234, …
$ deaths                    <int> 6, 9, 11, 10, 16, 13, 6, 26, 10, 18, 5, 19, …

echo

```{r}
#| echo: false

glimpse(NHSRdatasets::covid19)
```

#| echo

Echo shows the code and when it’s set to false code is hidden

Rows: 61,900
Columns: 7
$ date_reported             <date> 2020-12-14, 2020-12-13, 2020-12-12, 2020-12…
$ continent                 <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, As…
$ countries_and_territories <fct> "Afghanistan", "Afghanistan", "Afghanistan",…
$ country_territory_code    <fct> AFG, AFG, AFG, AFG, AFG, AFG, AFG, AFG, AFG,…
$ population_2019           <int> 38041757, 38041757, 38041757, 38041757, 3804…
$ cases                     <int> 746, 298, 113, 63, 202, 135, 200, 210, 234, …
$ deaths                    <int> 6, 9, 11, 10, 16, 13, 6, 26, 10, 18, 5, 19, …

eval

```{r}
#| eval: false

glimpse(NHSRdatasets::covid19)
```

#| eval

eval is short for evaluate which means the code is run. If there is a bug the report won’t run.

glimpse(NHSRdatasets::covid19)

include

```{r}
#| include: false

glimpse(NHSRdatasets::covid19)
```

#| include

  • include default is true and when set to false will prevent any output (code or results) from being included in the output.

  • This includes the {tidyverse} message.

  • The code is still run and available to subsequent chunks.

Warning

Gif of RStudio console with library(tidyverse) being typed, run and the information on what is loaded is shown.

Hiding warnings

This can be done in chunks:

```{r}
#| warning: false

library(tidyverse)
```

Chunk option summary

More details are online in the Quarto documentation

  • RMarkdown formats can also be used in Quarto, it’s backwards compatible
  • Options are started with #| which has no short cut key currently…
  • … but after the first line a return copies this format
  • Chunk options in RStudio Quarto have auto fill prompts

Naming chunk labels

```{r}
#| label: peek

glimpse(NHSRdatasets::covid19)
```

Don’t repeat labels!

  • Duplicating chunk labels will break the report if you have other content in it but not if you are referring to an earlier chunk to recycle the code
  • ref-label: can also be used instead of label:

Erroring:

processing file: covid-report.qmd
Error in parse_block(g[-1], g[1], params.src, markdown_mode) : 
  Duplicate chunk label 'covid-chart', which has been used for the chunk:
library(tidyverse)
library(NHSRdatasets)

local_covid <- NHSRdatasets::covid19 |>
  filter(countries_and_territories == params$site)
Calls: .main ... process_file -> split_file -> lapply -> FUN -> parse_block
Execution halted

Your turn!

In the report covid-analysis.qmd:

  • Name two existing code chunks using label: test
  • Render the report (see the error)
  • Remove the label from the second chunk
  • Create a new chunk and call that ref-label: test
  • Put in opposite chunk options to the first for eval: and echo:, render and see the difference
08:00

Global settings

Chunk options can be set once at the YAML and to apply the whole report.

execute: 
  echo: false
  eval: false
  warning: false

Next Section