Skip to Main Content

Intro to R Programming

R is a powerful tool for data analysis and visualization; this guide will provide resources to get you started with this programming language!

Set up the Working Directory

For every new R session, be sure to set your Working Directory (wd), where R will look for and save files.

Make a folder for your project in a known location on your computer.
You have two options for setting up: 
1. Under the 'Session' tab on the top bar, go to 'Set Working Directory' and then 'Choose Directory'
2. In the Script Editor, type the code setwd("filepathname"). Check the working directory path with the getwd() function.

 

If you are using Posit Cloud, find saved projects in 'Your Workspace.’ Saved RStudio sessions will be listed, with options to copy, delete, export, or share R script and history files.

Saving an R Session

When you are working in RStudio, save every step of your data analysis in a .R script file.

Write comments in your scripts with # to explain the purpose of a certain line of code, or to visually separate chunks of code. Lines of text starting with # will not be run on R.

To save your R code in the Script Editor, click ‘Save’ under the ‘File’ menu, click the 'Save' floppy disk icon, or use keyboard shortcuts Ctrl+S (Windows) or Cmd+S (Mac). Unsaved scripts, or edits to previously saved scripts in the Script Editor pane will have red text and an asterisk in the file name.

Closing an R Session

To close RStudio, you have three options:

  1.  Under ‘File’, click ‘Quit Session’
  2.  'X' out the window in the top right corner
  3.  Run the code q() or quit() in the Script Editor

You may be prompted to save the workspace image when quitting. Don’t save the workspace image unless (a) you’re working on something that takes a lot of processing time (i.e., very large data sets or complex analyses) or (b) you’re near completing your project and only making minor tweaks.

Start a new R session each time, without any R objects. This will ensure codes run without potential mistakes from the last session.