Solving Bigger Problems (reference card)

Problem Decomposition

  1. Understand the problem
  2. Break the problem down into manageable pieces
  3. Code one small piece at a time and check that it works

Basic Debugging

  1. Read the error message
  2. Hypothesize about what is wrong
  3. Make one change that is expected to fix error
  4. Check if change worked/fixed error

Paths

Paths tell us where something is stored.

Absolute Paths

These paths give the full location on the computer and start with a /.

On macOS and Linux they typically start with /home/username:

"/home/username/project_folder/data.csv"

On Windows they typically start with Users/username:

"/Users/username/project_folder/data.csv"

Windows may display paths with backslashes (\) instead of forward slashes (/), but you should always use forward slashes in R since it will make your code work on all operating systems.

It is generally a bad idea to use absolute paths in your code because it won’t run on other computers. It is better to use relative paths (see below).

Relative Paths

These paths are relative to the current working directory and do not start with a /.

To refer to a file in the current directory:

"data.csv"

To refer to a file in a subdirectory:

"subfolder/data.csv"

Working directory

To find out what the current working directory is in R:

getwd()

Don’t use setwd() to change the working directory in R scripts. Instead, use RStudio projects (see below).

Projects

RStudio projects make it easy to manage the working directory and files for a project.

  • Open RStudio and then navigate to File > New Project
  • Select New Directory
  • Select New Project
  • Provide a name and location for the project

The location of the project will be the working directory.

To switch between projects, use File > Recent Projects or File > Open Project.