Programming elements
Pipes in R
Pipes are an extremely useful tool from the magrittr package1 that allow you to express a sequence of multiple operations. They can greatly simplify your code and make your operations more intuitive.
Practice the pipe
library(tidyverse) library(rcis) Using gun_deaths from the rcis library, answer the following question: For each education category, how many white males where killed in 2012? Write your code using all four methods:
Functions in R
library(tidyverse) library(palmerpenguins) Run the code below in your console to download this exercise as a set of R scripts. usethis::use_course("cis-ds/pipes-and-functions-in-r") Functions are an important tool in the computational social scientist’s toolkit.
Vectors
library(tidyverse) library(rcis) set.seed(1234) Run the code below in your console to download this exercise as a set of R scripts. usethis::use_course("cis-ds/vectors-and-iteration") So far the only type of data object in R you have encountered is a data.
Iteration
library(tidyverse) library(rcis) library(palmerpenguins) library(modeldata) set.seed(1234) theme_set(theme_minimal()) Run the code below in your console to download this exercise as a set of R scripts. usethis::use_course("cis-ds/vectors-and-iteration") Writing for loops Functions are one method of reducing duplication in your code.
Bugs and styling code
library(tidyverse) set.seed(1234) Admiral Grace Hopper discovered the first bug in a computer Run the code below in your console to download this exercise as a set of R scripts.
Debugging and condition handling
library(tidyverse) set.seed(1234) theme_set(theme_minimal()) Run the code below in your console to download this exercise as a set of R scripts. usethis::use_course("cis-ds/debugging-and-defensive-programming") Conditions are a method for communicating to the user when something unanticipated has occurred.
Generating reproducible examples
Run the code below in your console to download this exercise as a set of R scripts. usethis::use_course("cis-ds/reproducible-examples") Include a reproducible example Including a minimal, complete, and verifiable example of the code you are using greatly helps people resolve your problem in your code.