3  Workflow: basics


  1. Why does this code not work?

my_variable <- 10
Error in eval(expr, envir, enclos): object 'my_varıable' not found

The i is dotless in the call of my_variable and so doesn’t match.

Quarto chunk error: true

In Quarto this chunk ran using error: true which shows the error in the book, useful for instances where code errors are shared in Quarto presentations or on websites!

  1. Tweak each of the following R commands so that they run correctly:


ggplot(dTA = mpg) + 
  geom_point(maping = aes(x = displ y = hwy)) +
  geom_smooth(method = "lm)


── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) +
  geom_smooth(mapping = aes(x = displ, y = hwy),
              method = lm)
`geom_smooth()` using formula = 'y ~ x'

There are a lot of corrections needed in this code. It includes:

  • todyverse should be tidyverse)
  • dTA instead of data)
  • maping instead of mapping
  • missing , between x = displ and y = hwy
  • a " before "lm
Quotations around the lm in method = (note)

"lm" will work but RStudio will flash up an error in the margin saying unexpected token if you click on the red circle with white cross.

  • geom_smooth() also requires its own mapping information as the aes() isn’t available to that line. If this were global it would be:

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + 
  geom_point() +
  geom_smooth(method = lm)
`geom_smooth()` using formula = 'y ~ x'

  1. Press Option + Shift + K / Alt + Shift + K. What happens?

The keyboard shortcuts overlay menu comes up in RStudio.

How can you get to the same place using the menus?

Tools/Keyboards Shortcuts Help

  1. Let’s revisit an exercise from the https://r4ds.hadley.nz/data-visualize#sec-ggsave. Run the following lines of code.

my_bar_plot <- ggplot(mpg, aes(x = class)) +
my_scatter_plot <- ggplot(mpg, aes(x = cty, y = hwy)) +
ggsave(filename = "mpg-plot.png", plot = my_bar_plot)

Which of the two plots is saved as mpg-plot.png?

The bar plot from the object my_bar_plot is saved.


This has been explicitly detailed in the ggsave() function. Both plots are also saved as objects (https://r4ds.hadley.nz/workflow-basics#sec-whats-in-a-name) so they can be referred to in the function.