R for Data Science Exercises: Workflow Basics

These exercises are an introduction to the workflow basics of R, including being mindful of typos in code and keyboard shortcuts for faster coding!

R for Data Science Exercises: Workflow Basics

R for Data Science 2nd Edition Exercises (Wickham, Mine Çetinkaya-Rundel and Grolemund, 2023)

Workflow Basics

Run the code in your script for the answers! I'm just exploring as I go.

Workflow Basics Exercises

Packages to load

library(tidyverse)
  1. Why does this code not work?

Error Code:

  • my_variable <- 10 // my_varıable

The error occurs as the variable names do not match. The variable is called my_variable (i) while the next line calls it my_varıable, with an an ı (i with no dot).

Correct Code:

my_variable <- 10
my_variable
  1. Tweak each of the following R commands so that they run correctly:

Error Code:

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

Changes:

  • todyverse changed to tidyverse.

  • ggplot(dTA = mpg) + geom_point(maping = aes(x = displ y = hwy)) + changed to ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() +.

  • geom_smooth(method = "lm) changed to geom_smooth(method = "lm").

Correct Code:

library(tidyverse)

ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point() +
  geom_smooth(method = "lm")
  1. Press "Option + Shift + K" or "Alt + Shift + K". What happens? How can you get to the same place using the menus?

"Option + Shift + K" or "Alt + Shift + K" shows the keyboard shortcuts available. You can also go to the menu bar: Tools > Keyboard shortcuts help.

  1. Run the following lines of code. Which of the two plots is saved as mpg-plot.png? Why?
my_bar_plot <- ggplot(mpg, aes(x = class)) +
  geom_bar()
my_scatter_plot <- ggplot(mpg, aes(x = cty, y = hwy)) +
  geom_point()
ggsave(filename = "mpg-plot.png", plot = my_bar_plot)

my_bar_plot object is saved, as it is specified in the plot argument of the ggsave() call. The filename argument will save the plot as "mpg-plot.png". Typing ?ggsave() in the console or searching for ggsave() in help will show the documentation and arguments for ggsave().

Reference

Wickham, H., Mine Çetinkaya-Rundel and Grolemund, G. (2023) R for data science. 2nd ed. Sebastopol, CA: O’Reilly Media.