Skip to main content

19  Using the pipeline to build research output

While creating pipelines can be incredibly helpful for managing projects and creating reproducible analyses, it can also be very difficult to build them effectively and in a manageable way. In this session, we will build out our pipeline that we previously designed, by building up pieces towards our end product. We will use functional programming to design and create our functions that will create each of our pipeline’s products.

19.1 Learning objectives

  1. Build the outputs of an analysis pipeline in targets after the design phase.
  2. Use the principle of “start at the end” to guide your work and build your pipeline effectively.
  3. Apply a function-oriented and functional programming approach to writing code and producing research output that integrates easily into the pipeline.

19.2 💬 Discussion activity: Recall and share what you’ve learned so far

Time: ~6 minutes.

A very effective way to learn is to recall and describe to someone else what you’ve learned. So before we start this session, take some time to think about what you’ve learned so far from this workshop.

  1. Take 1-2 minute and try to recall as much as you can about what you’ve done over the last two days. Without looking at your notes or the other sections of the website, try to remember things about importing and robust functions.
  2. Then, for 4-5 minutes, share with your neighbour what you remember and try to describe it to each other. Maybe you will each remember different things.

19.3 Building our next “product”: A table of basic descriptive statistics

Time to make our next “product”! Recalling from Figure 18.6, we finished the first two targets for loading in the data into R from the file. We also added the tar_read() link to the report from the table and figure. Also recall that we decided to call our table product table_descriptive_stats and to call the function that makes it create_table_descriptive_stats(). This function will take the cv_risk data as input (the first argument) and return the table_descriptive_stats as output.

graph BT
    data_file["data_file<br>'data/cv-risk.csv'"]:::done -->|"read_csv()"| cv_risk:::done
    cv_risk -->|"create_table_descriptive_stats()"| table_descriptive_stats:::wip
    cv_risk -->|"create_plot_counts()"| plot_counts:::wip
    table_descriptive_stats -->|"tar_read()"| report:::wip
    plot_counts -->|"tar_read()"| report:::wip

    classDef done stroke-width:3px
    classDef wip fill:#ffedd6
Figure 19.1: Current status on pipeline, next to build is the table.

To make the table_descriptive_stats from cv_risk, we’ll have to do some wrangling. We’ll use functions from tidyverse, specifically dplyr. We don’t yet have tidyverse added to our dependencies, so let’s add it! Because tidyverse is a “meta”-package (special type of package that makes it easy to install and load other packages), we need to add it to the "depends" section of the DESCRIPTION file. The "depends" label is also used for build dependencies, but you almost never need to use this label

Console
use_package("tidyverse", "depends")
Note

If you try to run this code without using "depends", you’ll get an error that explains why you can’t do that.

Since we’ll be prototyping code first before making it a function, we’ll use the docs/sandbox.qmd file. Let’s open up the docs/sandbox.qmd file and add library(tidyverse) to the setup code chunk, so that we can use the functions from tidyverse. We’ll also use library() for targets, set the “store”, and load the cv_risk data like we did in docs/report.qmd. Put it at the top of the setup code chunk, like below:

docs/sandbox.qmd
```{r setup}
library(tidyverse)
library(targets)
tar_config_set(store = here::here("_targets"))
cv_risk <- tar_read(cv_risk)
```

Then, below this code chunk, we’ll create a new header at the bottom of the file and code chunk with Ctrl-Alt-I or with the Palette (Ctrl-Shift-P, then type “new chunk”).

docs/sandbox.qmd
## Making a table

```{r}
```

There are many different descriptive statistics we could use for the table, as well as different variables to include in it. Two commonly used descriptive statistics are the mean and standard deviation (SD). In our case, we could calculate the mean and SD for all number variables and display those statistics in our table. Because making tables nice and pretty can take a fair amount of time and tweaking, we will keep it simple and make a rather rough looking table.

Tip

There are many R packages that provide some functions to simplify making a “table 1”, for example tableone, gtsummary, or janitor. There are also many packages that provide functions for general-purpose table-making and styling, such as gt or kableExtra. They all have their pros and cons and depend on your specific needs. For this workshop, we want to focus on building reproducible workflows, rather than specifics about making nice looking output.

What we’d like to create is a (very rough) table that looks a bit like the below:

Variables Mean SD
Variable 1 1.2 0.2
Variable 2 23.34 1.24

However, our data currently looks like:

# A tibble: 500 × 19
   patient_id gender   age systolic_blood_pressure total_cholesterol
   <chr>      <chr>  <dbl>                   <dbl>             <dbl>
 1 CARD-00001 men       46                    127.              249.
 2 CARD-00002 men       54                    122.              226 
 3 CARD-00003 men       47                    140.              179.
 4 CARD-00004 women     75                    163.              267 
 5 CARD-00005 women     66                    129.              199.
 6 CARD-00006 women     82                    147.              245.
 7 CARD-00007 men       67                    137.              253.
 8 CARD-00008 men       55                    125.              196 
 9 CARD-00009 women     41                     90               168.
10 CARD-00010 women     63                    175.              246.
# ℹ 490 more rows
# ℹ 14 more variables: high_density_lipoprotein <dbl>,
#   low_density_lipoprotein <dbl>, body_mass_index <dbl>, hba1c <dbl>,
#   smoking <lgl>, diabetes <lgl>, hypertension <lgl>,
#   atrial_fibrillation <lgl>, family_history_cvd <lgl>,
#   alcohol_use <lgl>, score2_10y <dbl>, ascvd_pce_10y <dbl>,
#   outcome_any_cv_event <lgl>, outcome_death <lgl>

We’ll need to use a mix of pivoting and using split-apply-combine, which we covered in the split-apply-combine session of the intermediate workshop, to get to the right structure. Representing this visually, where each node is a data frame, it might look like:

Slowly walk through this diagram, explaining each step and why we have these steps. Then, verbally walk through which functions we want to use to get to each step.

flowchart TB
    cv_risk -->|"select()<br>numeric only"| only_numeric
    only_numeric -->|"pivot_longer()"| long_format
    long_format -->|"group_by()"| by_variable
    by_variable -->|"summarise()"| calculate_mean_sd
Figure 19.2: Steps for transforming our data into the final table format.

The functions to create each object might be something like:

  1. select() to keep only the variables that are numeric with where() and is.numeric().
  2. pivot_longer() to get the data so that there is at least two columns, one for the variables names and one with the variables’ values. Each row should be for a single variable rather than for a participant.
  3. group_by() to split the dataset by the variables of interest.
  4. summarise() with across() to calculate the mean() and standard deviation (sd()) for each variable.

For step 4 with summarise(), we could either directly create or modify columns with e.g. summarise(mean_value = ...) or we could use the across() functional. With across(), it makes the code a bit more robust and “extensible” so that it can apply one or more transformations on one or more columns. By using this function, we don’t need to explicitly write out the names of the new columns, we can let across() auto-create them.

If we look at the help documentation of ?across (and by recalling from the intermediate workshop), we can give across() a list() that contains multiple functions to apply to our columns.

Slowly build up this pipe of functions, running it each time you add a function to the pipe. Explain what the code is doing and why at each step.

Let’s write out the code we planned above in the code chunk that we just created:

docs/sandbox.qmd
cv_risk |>
  select(where(is.numeric)) |>
  pivot_longer(everything()) |>
  group_by(name) |>
  summarise(across(value, list(mean = mean, sd = sd)))
# A tibble: 9 × 3
  name                     value_mean value_sd
  <chr>                         <dbl>    <dbl>
1 age                         58.3     11.7   
2 ascvd_pce_10y                0.123    0.141 
3 body_mass_index             29.3      6.82  
4 hba1c                        5.58     0.913 
5 high_density_lipoprotein    54.1     16.5   
6 low_density_lipoprotein    113.      36.8   
7 score2_10y                   0.0751   0.0954
8 systolic_blood_pressure    129.      23.4   
9 total_cholesterol          205.      34.3   

After we’ve made it, let’s style the file using the Palette (Ctrl-Shift-P, then type “style file”). Then, commit the changes to the Git history with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”).

Now that we’ve made this code, it’s time to convert it into our create_table_descriptive_stats() function so that we can then add it as a target in our pipeline. Time to try it on your own!

19.4 🧑‍💻 Exercise: Convert the table code into a function

You will need to copy this function into the R/functions.R file in order to do the next section. While they do the exercise, copy and paste the answer into your R project.

Time: ~15 minutes.

In the docs/sandbox.qmd file, use the function-oriented workflow, as taught in the intermediate workshop, to take the code we wrote above and convert it into a function. Start with making it into a function in the Quarto file first before moving it to the R/functions.R file. To help you get started, here is some scaffolding code:

```{r}
create_table_descriptive_stats <- function(data) {
  data |>
    ___
}

create_table_descriptive_stats(targets::tar_read(cv_risk))
```

Complete these tasks:

  1. Convert the code you wrote into a function by using the scaffold above, wrapping it with function() {...} and naming the new function create_table_descriptive_stats (already included in the scaffold).

  2. Paste the code we all wrote together into the body of the function. Replace cv_risk in the code we wrote with data and put data as an argument inside the brackets of function() (it will already be there from the scaffolding code).

  3. Append the name of the package that the functions come from that are inside your function. For example, add dplyr:: before group_by() because it’s from the dplyr package. Remember that you can look up which package a function comes from by writing ?functionname in the Console. ALL non-base R functions used inside your function must have the package name appended to them.

  4. Run use_package() for the (1) package you used inside your function that is not already in the DESCRIPTION file.

  5. Style the code using the Palette (Ctrl-Shift-P, then type “style file”) to make sure it is formatted correctly.

  6. Place your cursor inside the function and add some Roxygen documentation with Ctrl-Shift-Alt-R or with the Palette (Ctrl-Shift-P, then type “roxygen comment”). Remove the lines that contain @examples and @export, then fill in the other details (like the @params and Title). In the @return section, write “A data.frame/tibble.”

  7. Cut and paste the function over into the R/functions.R file.

  8. Source the R/functions.R file with Ctrl-Shift-S or with the Palette (Ctrl-Shift-P, then type “source”), and then test the code out by running create_table_descriptive_stats(targets::tar_read(cv_risk)) in the Console. If it works, do the last task.

  9. Save both files (docs/sandbox.qmd and R/functions.R). Then open the Git interface and commit the changes you made to them with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Then push your changes up to GitHub.

TipTip: Implicit returns

In the intermediate workshop, we suggested using return() at the end of the function. Technically, we don’t need an explicit return(), since the output of the last code that R runs within the function will be the output of the function. This is called an implicit return and we will be using this feature throughout the rest of this workshop.

R/functions.R
#' Calculate descriptive statistics of each variable.
#'
#' @param data The CV risk dataset.
#'
#' @return A data.frame/tibble.
#'
create_table_descriptive_stats <- function(data) {
  data |>
    dplyr::select(tidyselect::where(is.numeric)) |>
    tidyr::pivot_longer(tidyselect::everything()) |>
    dplyr::group_by(name) |>
    dplyr::summarise(dplyr::across(value, list(mean = mean, sd = sd)))
}

Test that the function works after source()ing the R/functions.R file:

Console
create_table_descriptive_stats(targets::tar_read(cv_risk))

And run this to add tidyselect as a dependency.

Console
use_package("tidyselect")
CautionSticky/hat up!

When you’re ready to continue, place the sticky/paper hat on your computer to indicate this to the teacher 👒 🎩

19.5 🧑‍💻 Extra exercise: Make the table prettier

Time: ~5-15 minutes.

If you finished the above exercise and there is still time, you can try to do this exercise. Right now, the output from create_table_descriptive_stats() will be added into docs/report.qmd to create a table is not very pretty. So try to modify the create_table_descriptive_stats() function in R/functions.R to make the output nicer.

There are many ways you could improve the table. Below is a list of some potential ways. All of the listed ways below use code we covered throughout the intermediate workshop, so you can use that as a reference.

  • Rounding the numbers to one or two decimals. For example, using round() on numeric columns (e.g. where(is.numeric)) in a across() within a mutate().
  • Fixing the names of the columns to something that would be used in a table. For example, using select() or rename() at the end of the function.
  • Converting the names of the variables to be more human-readable. For example, using str_replace_all() to replace _ with a space.
  • Joining the mean and standard deviation columns together into a single value (and single column). For example, using mutate() and glue::glue() to combine the two columns into something that formats like MEAN (SD), e.g. 2.3 (0.2).

As you update the code, remember to:

  • Append the name of the package that the functions come from that are inside your function using ::.
  • Style the code using the Palette (Ctrl-Shift-P, then type “style file”) to make sure it is formatted correctly.
  • Use use_package() for any packages you used inside your function that is not already in the DESCRIPTION file. Any package you add as a dependency that is used inside your functions would be considered a build dependency.
  • Test your changes by sourcing the R/functions.R file with Ctrl-Shift-S or with the Palette (Ctrl-Shift-P, then type “source”), and then running create_table_descriptive_stats(targets::tar_read(cv_risk)) in the Console until the output looks like you want it to look like.

At the end, make sure to save R/functions.R and then open the Git interface and commit the changes you made to them with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Then push your changes up to GitHub.

These are some potential changes you could make to the function to make it prettier.

#' Calculate descriptive statistics of each variable.
#'
#' @param data The CV risk dataset.
#'
#' @return A data.frame/tibble.
#'
create_table_descriptive_stats <- function(data) {
  data |>
    dplyr::select(tidyselect::where(is.numeric)) |>
    tidyr::pivot_longer(tidyselect::everything()) |>
    dplyr::group_by(name) |>
    dplyr::summarise(dplyr::across(value, list(mean = mean, sd = sd))) |>
    # dplyr::mutate(name = name |>
    #   stringr::str_replace_all("_", " ")
    # ) |>
    # Round all number columns to one digit.
    dplyr::mutate(dplyr::across(
      tidyselect::where(is.numeric),
      \(x) round(x, digits = 1)
    )) |>
    # Join the mean and SD columns into one so it looks like, e.g. `2.3 (0.2)`.
    dplyr::mutate(MeanSD = glue::glue("{value_mean} ({value_sd})")) |>
    # Rename the columns so that they will look how you want them to look in
    # the table.
    dplyr::select(Variable = name, `Mean SD` = MeanSD)
}

Test it out in the Console with:

Console
create_table_descriptive_stats(targets::tar_read(cv_risk))

If you use the glue package, add it to the dependencies in the DESCRIPTION file:

Console
use_package("glue")

19.6 Adding the first “product” function to the pipeline

Now that we’ve created a function to calculate some basic statistics, we can now add it as a step in the targets pipeline. Open up the _targets.R file and go to the end of the file, where the list() and tar_target() code are found. Add a new tar_target() to the end of the list(). It should look like:

_targets.R
list(
  # ...,
  tar_target(
    name = table_descriptive_stats,
    command = create_table_descriptive_stats(cv_risk)
  )
)

Style the file using the Palette (Ctrl-Shift-P, then type “style file”). Next we can add this to our docs/report.qmd file and create an actual table. Open the docs/report.qmd file and go to the bottom of the file. Create a new header at the bottom of the file and a new code chunk below it with Ctrl-Alt-I or with the Palette (Ctrl-Shift-P, then type “new chunk”).

docs/report.qmd
## Results: Basic stats table

```{r}
```

In this code chunk we need to add the output from the targets target using tar_read(). We also want to convert the data frame into a nice Markdown table using knitr::kable() with a caption. So the code chunk should look like:

docs/report.qmd
tar_read(table_descriptive_stats) |>
  knitr::kable(
    caption = "Basic descriptive statistics on variables in the CV risk dataset."
  )
Basic descriptive statistics on variables in the CV risk dataset.
Variable Mean SD
age 58.3 (11.7)
ascvd_pce_10y 0.1 (0.1)
body_mass_index 29.3 (6.8)
hba1c 5.6 (0.9)
high_density_lipoprotein 54.1 (16.5)
low_density_lipoprotein 112.8 (36.8)
score2_10y 0.1 (0.1)
systolic_blood_pressure 128.6 (23.4)
total_cholesterol 204.9 (34.3)

Since we used knitr in docs/report.qmd, we need to add it as a build dependency:

Console
use_package("knitr")

Next, style the docs/report.qmd file using the Palette (Ctrl-Shift-P, then type “style file”). Now time for us to see if the pipeline builds! First, let’s see how the visualization looks. Run targets::tar_visnetwork() using the Palette (Ctrl-Shift-P, then type “targets visual”) to see that it now detects the new connections between the pipeline targets. Then, run targets::tar_make() with the Palette (Ctrl-Shift-P, then type “targets run”). Let’s run targets::tar_visnetwork() again with the Palette (Ctrl-Shift-P, then type “targets visual”) to see the updated pipeline graph. Neat eh! 🎉

When we run the pipeline, we should get an HTML file output from the Quarto document. Let’s open that up in a web browser to see the table we created! You can also render the Quarto document directly with Ctrl-Shift-K or with the Palette (Ctrl-Shift-P, then type “render”) to see the same output.

Before continuing, commit the changes to the Git history with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Then push your changes up to GitHub.

19.7 Creating figure outputs

Show this diagram again on the screen to remind the learners of the overall plan and the next steps.

Let’s return back to our current design and plan for our pipeline by look at our diagram again in Figure 19.3. We’ve now made our first product, the next is the figure!

graph BT
    data_file["data_file<br>'data/cv-risk.csv'"]:::done -->|"read_csv()"| cv_risk:::done
    cv_risk -->|"create_table_descriptive_stats()"| table_descriptive_stats:::done
    cv_risk -->|"create_plot_counts()"| plot_counts:::wip
    table_descriptive_stats -->|"tar_read()"| report:::wip
    plot_counts -->|"tar_read()"| report:::wip

    classDef done stroke-width:3px
    classDef wip fill:#ffedd6
Figure 19.3: Table product finished, next to build is the figure.

Since we’ve made a table for the continuous variables, let’s make a plot of the binary variables. For plotting binary variables, the best graph is a bar chart. We’ll have one bar chart per variable, which we can easily do by using facet_wrap() in ggplot2. As we did with the table, we need to use pivot_longer() to get the data frame into the long format that facet_wrap() needs. So we’ll use the same select() with pivot_longer() like we did above for the table.

We’ve learned that we can create data frames as outputs from our targets pipeline, but the nice thing with targets is that we can create other types of objects too, like figures!

Let’s write code to create our first plot product. Since we’ll use ggplot2 to make figures, let’s add it to our DESCRIPTION file as a build dependency.

Console
use_package("ggplot2")

Slowly build up this plot code, running it each time you add a new line/layer and explaining what it does and why we’re doing it.

Next, we’ll switch back to docs/sandbox.qmd and write the code to this plot of the counts of each binary variable. Create a new header at the bottom of the file and a new code chunk below it with Ctrl-Alt-I or with the Palette (Ctrl-Shift-P, then type “new chunk”).

docs/sandbox.qmd
## Plot of counts

```{r}
```

We’ll use geom_bar() for the bar chart. It requires only one column: the values of the variable. We can use pivot_longer() to get the data in long format, so we can easily use facet_wrap() to create a plot for each variable. The x axis will have the values of the variables and the facet_wrap() will contain the variable names, which are the two columns created when we use pivot_longer(). Like the table, we’ll make a very rough looking figure that isn’t very pretty. We just want to get an initially product created to put into the pipeline as a target.

docs/sandbox.qmd
cv_risk |>
  select(where(is.logical)) |>
  pivot_longer(everything()) |>
  ggplot(aes(x = value)) +
  geom_bar() +
  facet_wrap(vars(name))

We keep the figure very simple, as this workshop is about building reproducible pipelines, not making nice figures. Let’s style the document with the Palette (Ctrl-Shift-P, then type “style file”), then add and commit the changes to the Git history with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”), and lastly push the changes up to GitHub.

Next, it’s time for you to convert the code into a function.

19.8 🧑‍💻 Exercise: Convert the plot code to a function

Time: ~15 minutes.

For now, we will only take the code to make the bar plot and convert it into a function. Just like you did with the create_table_descriptive_stats() function in the exercise above, complete these tasks, using the scaffolding code below to help you get started:

docs/sandbox.qmd
create_plot_counts <- function(data) {
  data |>
    ___
}

create_plot_counts(targets::tar_read(cv_risk))
  1. Wrap the plot code inside docs/sandbox.qmd with function() {...} and use the name create_plot_counts, which is already given in the scaffold for the new function.

  2. Replace cv_risk with data and put data as an argument inside the brackets of function() (already done in the scaffolding code).

  3. Add the package name to the start of each function, e.g. ggplot2:: to the start of each ggplot2 function.

  4. Style using the Palette (Ctrl-Shift-P, then type “style file”) to make sure it is formatted correctly.

  5. With the cursor inside the function, add some Roxygen documentation with Ctrl-Shift-Alt-R or with the Palette (Ctrl-Shift-P, then type “roxygen comment”). Remove the lines that contain @examples and @export, then fill in the other details (like the @params and Title). In the @return section, write “A plot object.”

  6. Cut and paste the function over into the R/functions.R file.

  7. Source the R/functions.R file with Ctrl-Shift-S or with the Palette (Ctrl-Shift-P, then type “source”) and then test the code by running create_plot_counts(targets::tar_read(cv_risk)) in the Console. If it works, do the last task.

  8. Save both files and then open the Git interface and commit the changes you made to them with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Finally push your changes up to GitHub.

R/functions.R
#' Plot for basic counts of variables in the CV risk data.
#'
#' @param data The CV risk dataset.
#'
#' @return A plot object.
#'
create_plot_counts <- function(data) {
  data |>
    dplyr::select(tidyselect::where(is.logical)) |>
    tidyr::pivot_longer(tidyselect::everything()) |>
    ggplot2::ggplot(ggplot2::aes(x = value)) +
    ggplot2::geom_bar() +
    ggplot2::facet_wrap(ggplot2::vars(name))
}

And source and test that the code works with:

Console
create_plot_counts(targets::tar_read(cv_risk))

Continue to the next exercise if you’ve finished.

19.9 🧑‍💻 Exercise: Adding the plot function to the pipeline

Time: ~15 minutes.

Add the plot function you just created in the exercise above as a tar_target() item within the list() at the bottom of the _targets.R file and as an output in the docs/report.qmd file.

  1. Open the _targets.R file and add a new tar_target() to the end of the list(). Follow the same pattern as you’ve done with the other targets: Set name to plot_counts and command to create_plot_counts() with cv_risk as the argument.

  2. Style the file using the Palette (Ctrl-Shift-P, then type “style file”).

  3. Run targets::tar_visnetwork() using the Palette (Ctrl-Shift-P, then type “targets visual”) and run targets::tar_outdated() with the Palette (Ctrl-Shift-P, then type “targets outdated”) to see what has been changed.

  4. Run targets::tar_make() using the Palette (Ctrl-Shift-P, then type “targets run”) to run the pipeline with the added target.

  5. Re-run targets::tar_visnetwork() using the Palette (Ctrl-Shift-P, then type “targets visual”) to see the updated pipeline graph. You should see that the new item is now up to date.

  6. Open the docs/report.qmd file and go to the bottom of the file. Create a new header called ## Results: Counts of binary variables and add a new code chunk below it with Ctrl-Alt-I or with the Palette (Ctrl-Shift-P, then type “new chunk”). In this code chunk, use tar_read() to insert the output from the plot_distributions target and print it.

  7. Style the file using the Palette (Ctrl-Shift-P, then type “style file”).

  8. Run targets::tar_make() with the Palette (Ctrl-Shift-P, then type “targets run”) to build the pipeline again. Then run targets::tar_visnetwork() using the Palette (Ctrl-Shift-P, then type “targets visual”) to see the updated pipeline graph.

  9. Open the updated HTML file to check out how it now looks.

  10. If everything is good, then commit the changes to the Git history with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Then push your changes up to GitHub.

Add the plot function to the targets pipeline.

_targets.R
list(
  # ...,
  tar_target(
    name = plot_counts,
    command = create_plot_counts(cv_risk)
  )
)

And in the docs/report.qmd file, insert the figure with:

docs/report.qmd
tar_read(plot_counts)
CautionSticky/hat up!

When you’re ready to continue, place the sticky/paper hat on your computer to indicate this to the teacher 👒 🎩

19.10 🧑‍💻 Extra exercise: Make the plot prettier

Time: ~10-20 minutes.

If you’ve finished the last two exercises early and there is still time, you can try to improve the look of the plot and keep practicing the workflow of working with targets.

The current plot is quite ugly. There are several things you could start to improve on. You can use these below ideas as a starting point:

  • Use a nicer looking built-in theme. For example, any of the theme_*() ones like theme_classic().
  • Set custom x- and y-axis labels. For example, using labs().
  • Add a figure caption to the plot by adding #| fig-cap: "Your caption here" at the very top of the code chunk that has your tar_read() plot code in docs/report.qmd.
  • Fix the names of the variables. For example, using mutate() with snakecase::to_sentence_case() for a quick way of making variable names more human-readable.
  • Add colour by setting the fill to value in aes().
  • Use a different colour schema for the fill. For example, use scale_fill_viridis_d() or search for built-in colour schemas within scale_fill_.
  • Remove the legend since the variables are all only binary. For example, with the legend.position option in theme().

As you update the code, remember to:

  • Append the name of the package that the functions come from that are inside your function using ::.
  • Style the code using the Palette (Ctrl-Shift-P, then type “style file”) to make sure it is formatted correctly.
  • Use use_package() for any packages you used inside your function that is not already in the DESCRIPTION file. Any package you add as a dependency that is used inside your functions would be considered a build dependency.
  • Test your changes by sourcing the R/functions.R file with Ctrl-Shift-S or with the Palette (Ctrl-Shift-P, then type “source”), and then running create_plot_counts(targets::tar_read(cv_risk)) in the Console until the output looks like you want it to look like.
  • Use tar_outdated() and tar_visnetwork() in the Console (or by using the Command Palette Ctrl-Shift-P, then “targets outdated” or “targets visual”) to check the status.
  • Run tar_make() in the Console or with the Palette (Ctrl-Shift-P, then type “targets run”). Re-check for outdated targets and visualize the network again.
  • Check the updated HTML file to confirm that the plot has the improvements, either by opening the HTML file in the browser or by re-rendering the Quarto document with Ctrl-Shift-K or with the Palette (Ctrl-Shift-P, then type “render”).

At the end, make sure to save R/functions.R and then open the Git interface and commit the changes you made to them with Ctrl-Alt-M or with the Palette (Ctrl-Shift-P, then type “commit”). Then push your changes up to GitHub.

These are some potential changes you could make to the function to make it prettier.

R/functions.R
create_plot_counts <- function(data) {
  data |>
    dplyr::select(tidyselect::where(is.logical)) |>
    tidyr::pivot_longer(tidyselect::everything()) |>
    dplyr::mutate(
      name = snakecase::to_sentence_case(name)
    ) |>
    ggplot2::ggplot(ggplot2::aes(x = value, fill = value)) +
    ggplot2::geom_bar() +
    ggplot2::facet_wrap(ggplot2::vars(name)) +
    ggplot2::scale_fill_viridis_d() +
    ggplot2::theme_minimal() +
    ggplot2::theme(legend.position = "none") +
    ggplot2::labs(
      x = "Binary value",
      y = "Count"
    )
}

Test out the changes in the Console by running this command:

Console
create_plot_counts(targets::tar_read(cv_risk))

Using the fig.cap code chunk option would look like:

```{r}
#| label: fig-plot-counts
#| fig-cap: "caption here"

tar_read(plot_counts)
```

19.11 Summary

  • Aim to have each target do one thing and to use one function per target. This keeps things a bit easier for you to track and manage, and keeps the pipeline smaller and more manageable.

  • Build up functions to use within the targets to take as few input arguments as possible and only output one thing.

  • Insert output, including figures and tables, generated from the pipeline in Quarto files by using tar_read().

19.12 Survey

Please complete the survey for this session:

Feedback survey! 🎉

19.13 Code used in session

This lists some, but not all, of the code used in the section. Some code is incorporated into Markdown content, so is harder to automatically list here in a code chunk. The code below also includes the code from the exercises.

use_package("tidyverse", "depends")
cv_risk |>
  select(where(is.numeric)) |>
  pivot_longer(everything()) |>
  group_by(name) |>
  summarise(across(value, list(mean = mean, sd = sd)))
list(
  # ...,
  tar_target(
    name = table_descriptive_stats,
    command = create_table_descriptive_stats(cv_risk)
  )
)
tar_read(table_descriptive_stats) |>
  knitr::kable(
    caption = "Basic descriptive statistics on variables in the CV risk dataset."
  )
use_package("knitr")
use_package("ggplot2")
cv_risk |>
  select(where(is.logical)) |>
  pivot_longer(everything()) |>
  ggplot(aes(x = value)) +
  geom_bar() +
  facet_wrap(vars(name))