💻 🏦
Code You Can Bank On

Introduction, workflow, setup

Amelia McNamara

Getting these materials

At least at first, it should be totally adequate to follow along with the slides I’m sharing on the screen. But I know people like to have all the materials!

Everything is available on GitHub, https://github.com/AmeliaMN/CodeYouCanBankOn /

If you are a git/GitHub user, you can fork and clone this repo. /

If you’re not, you can download everything as a zip file

About me

I’m an Associate Professor of data science at the University of St. Thomas, and a proud R-lady. I’ve taught a ton of workshops like this over the years, from Software Carpentry to rstudio::conf to NICAR and everything in between.


The materials you’ll be seeing from me have been modified from a number of sources, including:

One huge feature of the R community is that everyone is so generous with their time, expertise, and materials. Almost everything (including this workshop!) is Creative Commons licensed, so others can remix and reuse as they see fit.

“Everything I know is from Jenny Bryan”

Prerequisite knowledge

I am assuming you have a baseline familiarity with

  • R as a language
  • Writing functions
  • Markdown (RMarkdown/Quarto/plain Markdown)
  • git/GitHub

Catch up

I’ll do a little bit of review of each of those topics, but if they are totally new to you, here is some background reading to help you get caught up.

Packages

We’re going to be using the following packages, so make sure they are installed!

install.packages(c("forecast", "fredr", "imputeTS", 
                   "rlang", "roxygen2", "styler", "testthat", 
                   "tidyverse", "usethis", "vdiffr"))

Workflow and best practices

Workflow

Starting from a blank slate

We’re going to strive not to be data-hoarders

Tools -> Global Options

Restore .RData into workspace at startup: unchecked

Save workspace to .RData on exit: Never

Relative paths

  • Files should be stored in folders (also called directories) in some intelligible way, and any references to files should be “relative” rather than “absolute” paths. e.g.,
    ../Data/InputData/some_file.csv, 

rather than

    /Users/myUserName/Documents/Project/Data/InputData/some_file.csv

Use Projects

One way to avoid absolute file paths is to use RStudio Projects. Projects are basically directories (folders) that RStudio maintains a bit more information about.

To make a project, go to File -> New Project. You can either make a project out of an existing directory, or RStudio will create the directory for you if you’re starting from scratch!

(if you haven’t already downloaded the materials, you could make a New Project from Version Control!)

File organization

The TIER Protocol is one suggested organizational method

  • Project/
    • The Read Me File
    • The Report
    • Data/
      • InputData/
        • Input Data Files
        • Metadata/
          • Data Sources Guide
          • Codebooks
      • AnalysisData/
        • Analysis Data Files
        • The Data Appendix
      • IntermediateData/
    • Scripts/
      • ProcessingScripts/
      • DataAppendixScripts/
      • AnalysisScripts/
      • The Master Script
    • Output/
      • DataAppendixOutput
      • Results

Naming things

You need to name your files. Names should strive to be:

  • machine readable
  • human readable
  • useful with default ordering

Naming things

NO

  • my abstract.docx
  • Joe’s Filenames Use Spaces and Punctuation.xlsx
  • figure I.png
  • fig 2.png
  • JW&^(2sl@deletethisandyourcareerisoverWx2*.txt

YES

  • 2014-06-08_abstract-for-sla.docx
  • joes-filenames-are-getting-better.xlsx
  • fig01_scatterplot-talk-length-vs-interest.png
  • fig02_histogram-talk-attendance.png
  • 1986-01-28_raw-data-from-challenger-o-rings.txt

Via Jenny Bryan

Tidyverse style guide

There used to be several competing style guides for R code style, but many (most?) people have coalesced around the tidyverse style guide. Some organizations have modifications of the guide, like Google’s R style guide.

Tidyverse style uses snake_case rather than CamelCase.

Generally, variable names should be nouns and function names should be verbs. Strive for names that are concise and meaningful (this is not easy!).

Setting up for development

Set up your .Rprofile

The usethis package allows you to add default information about you that will be used in package development.


Edit your .Rprofile with usethis::edit_r_profile:

usethis::edit_r_profile()


to set the following options….

Set up your .Rprofile

options(
  usethis.full_name = "Amelia McNamara",
  usethis.description = list(
    `Authors@R` = 'person("Amelia", "McNamara",
          email = "amelia.mcnamara@stthomas.edu",
          role = c("aut", "cre"))'
  )
)

Set up your .Rprofile

Load devtools and testthat on start up


if (interactive()) {
  suppressMessages(require(devtools))
  suppressMessages(require(testthat))
}


Restart R for these to take an effect.

Grabbing some data

We’re going to be using some data from FRED as we work, so we need to go get it first.

library(fredr)

This package makes it easier to get FRED data, but it does require an API key. Request an API key

FRED

FRED

Adding API key to Renviron

usethis::edit_r_environ()

add your API key like this (replace with your own key)

FRED_API_KEY='abcdefghijklmnopqrstuvwxyz123456'


Save .Renviron

Restart R

Tomato prices

From FRED

library(fredr)
tomatoes <- fredr(
  series_id = "APU0000712311",
  observation_start = as.Date("2016-08-01"),
  observation_end = as.Date("2026-08-10")
)

Save the data (your turn)

We’d rather not be using the API every time we want to play with this data, so let’s save it as a local CSV.

readr::write_csv(tomatoes, "tomatoes.csv")

Read the data back in (your turn)

When I save out data, I always do a quick test to make sure I did it right!

tomatoes2 <- readr::read_csv("tomatoes.csv")

Looks good!

Make a plot (your turn)

Let’s do some quick EDA. What does the tomato price data look like?

Getting a little more data (your turn)

I’d also like data on the average price of bacon (sliced), and iceberg lettuce. Can you find those API endpoints and grab the data for the past ten years on them?

Save the datasets as .csv files so we can access them without hitting the API again.

Resources