Course contents
Part IChapter 2R foundations and data
Set Up R and RStudio
On this page
1. Install the tools
Step A (R): Download the current version for your operating system from CRAN. Run the installer with its defaults. R is the engine.
Step B (RStudio Desktop): Download the free RStudio Desktop application from Posit. Install and open it. RStudio is the working environment.
Step C (Quarto, optional initially): You can skip this for now. Later, install the Quarto CLI if you want to turn your own code and notes into a report. The Quarto installer is separate from an R package.
Step D (Practice files): Download the practice bundle, r-for-ehr-practice.zip, from the Download practice bundle button on this course’s page on the website. Unzip the whole folder into a simple place such as Documents. It holds the project file, the practice dataset, and the R scripts the chapters ask you to run.
Step E (Project): In RStudio choose File → Open Project and open R_Tutorial_Revision.Rproj. If this file is missing, use File → New Project → Existing Directory and select the unzipped R_Tutorial_Revision folder.
Example: a learner, Sam, installs R version 4.x from CRAN, then RStudio. Sam opens RStudio, not R itself, because RStudio finds R on its own. Under the Console tab, the first lines print the R version number. That printout is the check that Step A worked. Sam then downloads r-for-ehr-practice.zip, unzips it into Documents, and opens R_Tutorial_Revision.Rproj. The title bar now shows the project name, which is the check that Step E worked.
2. Meet the four RStudio panes
The Source pane is where scripts are written; the Console is where instructions run and results appear; Environment/History shows named objects; Files/Plots/Packages/Help helps locate files, view graphs, and find documentation. Pane layouts may vary.
Figure explanation: Look first for the Console (where commands run), then the Source editor (where your saved instructions go). Your pane arrangement may differ.
A script is a text file ending in .R. Unlike a word-processing document, a script contains instructions. Create a blank script with File → New File → R Script, then save it as my_first_script.R in the project folder.
In the script, type:
height_cm <- 165
height_m <- height_cm / 100
height_m
Select all three lines, then press Ctrl+Enter (Windows) or Cmd+Enter (Mac). You should see 1.65. If you type the same commands in the Console, they run immediately; in a script, they remain available for next time.
Example: type height_cm <- 165 in the script, select the line and press Ctrl+Enter. The line is copied to the Console, which prints nothing, but the Environment pane now lists height_cm with the value 165. Run height_m <- height_cm / 100 and then height_m: the Console prints [1] 1.65 and the Environment shows two objects. Pane by pane: the Source pane holds the three lines, the Console shows what ran, and the Environment lists height_cm and height_m.
3. Files and working directories
A path tells the computer where to find a file. A relative path starts at the project folder, so data/synthetic_ehr.csv works for every group member using the same project. Avoid hard-coded paths like C:/Users/Someone/Desktop/file.csv.
getwd() # Where is R looking right now?
On your computer this prints the project folder, for example [1] "C:/Users/you/Documents/R_Tutorial_Revision" (your path will differ).
file.exists("data/synthetic_ehr.csv") # TRUE if the sample file is in place
Output
[1] TRUElist.files("data") # Files inside the data folder
Output
[1] "synthetic_ehr.csv"If file.exists() is FALSE, check whether you opened the correct project and whether the ZIP was unzipped completely. Do not blindly use setwd(); opening the project is easier to reproduce.
Example: getwd() would print the project folder; if it ends with your project folder name, R is looking in the right place. The chunk that runs prints TRUE if data/synthetic_ehr.csv is where R expects it, and then the names of the files in data. TRUE means the relative path will work in every later chapter, and synthetic_ehr.csv should be in the list.
4. Start a new project in a new directory
The course bundle already contains a project, but you will want one of your own for every new analysis. A project is a folder that RStudio opens with its working directory set to that folder, so relative paths keep working.
- Choose File → New Project → New Directory → New Project.
- Type a folder name such as
clinic_analysis, and use Browse to pick where the folder will be created (for example, Documents). - Click Create Project. RStudio makes the folder, writes a
clinic_analysis.Rprojfile inside it, and reopens with that folder as the working directory.
Check it in the Console with getwd(): the path should end in clinic_analysis. Put your own scripts and data in this folder and they will be found by relative paths.
Example: a learner names the new project clinic_analysis and puts it in Documents. RStudio creates Documents/clinic_analysis/ with clinic_analysis.Rproj inside. The learner copies synthetic_ehr.csv into a data subfolder there, so read_csv("data/synthetic_ehr.csv") finds it from that project. If the learner instead opens R in another folder, getwd() shows a different path and the same line fails with 'data/synthetic_ehr.csv' does not exist in current working directory, which is why we open the project first.
5. Packages are add-ons
R comes with many built-in functions. A package adds more functions. You install a package once on a computer and load it in each new R session.
In the Console (internet needed for installation), run:
source("scripts/01_install_packages.R")
This runs the included installer, which installs the core packages the course uses. A few later chapters (such as 19 and 24) name an extra package and show how to install it there. You do not load packages in the Console for the course: each chapter starts with the library() lines it needs. A package can show startup messages; these are not necessarily errors. If installation fails, check internet access, R version, disk permissions, and whether you need system build tools. Ask a mentor and include the exact error message.
The tidyverse is not one package but a family of packages that share a style, including dplyr (tables), ggplot2 (plots), and tidyr (reshaping). library(tidyverse) attaches the core members of the family at once. Early chapters instead load the individual packages they need, such as dplyr, readr and ggplot2, so you can see which package each function comes from; the modeling chapters load tidymodels.
library(dplyr)
library(ggplot2)
If a line like this runs with no error, the package is installed and loaded. Chapters later in the course start with the library() lines they need.
Example: run library(dplyr) as in the chunk above. A silent return means it is installed and loaded. If you typed library(dplyr2) instead, R would stop with an error saying there is no package called dplyr2; that message means “not installed or misspelled”, not “R is broken”.
6. What is a file extension?
.R: R commands..csv: a plain-text table, one row per line..qmd: a Quarto document containing text and runnable code..Rproj: RStudio project configuration..html: a website/page produced by rendering.
Example: the extensions of the files this course asks you to create can be read with tools::file_ext(), a function from the tools package that ships with R.
files <- c("my_first_script.R", "synthetic_ehr.csv", "my_report.qmd",
"clinic_analysis.Rproj", "my_report.html")
tools::file_ext(files)
Output
[1] "R" "csv" "qmd" "Rproj" "html" The printout is "R", "csv", "qmd", "Rproj" and "html", one per file name. If a file you expect to be a script prints "txt", it was saved as plain text and RStudio will not treat it as R code.
7. Make a report from a .qmd file
A .qmd file mixes ordinary text with code, and Render turns it into one finished report (usually an HTML page). It needs Quarto, which is installed with recent versions of RStudio or from the Quarto link in Step C.
- Choose File → New File → Quarto Document, give it a title, and click Create.
- Save it in your project folder as
my_report.qmd. - In the text, a line that starts with
#is a heading; more#signs make a smaller heading. Add a few lines like this:
# My first report
## Height
Height in meters:
```{r}
height_m <- 165 / 100
height_m
```
- Click the Render button above the editor. RStudio runs every code chunk, then opens
my_report.htmlshowing your headings, the code, and its output.
Each time you change the file, Render again; the report is rebuilt from scratch, which is why it is reproducible.
Example: with the my_report.qmd above, the rendered page shows the large heading “My first report”, the smaller heading “Height”, the sentence “Height in meters:”, the code height_m <- 165 / 100, and under it the output [1] 1.65. Change 165 to 170, Render again, and the output becomes [1] 1.7 without any other edit.
8. Repeatability check
Close RStudio and reopen the project. Re-run your script. If it works in a fresh R session, you are beginning to build reproducible analyses.
Example: you write height_m <- height_cm / 100 in your script but forgot the line height_cm <- 165 above it. It worked yesterday only because height_cm was still in your session. After reopening the project, R reports “object ‘height_cm’ not found”. Putting both lines in the script, in order, fixes it, and now the script works for anyone from a fresh start.
Try it
- Create and save a script that calculates
165 / 100and prints the result.
Show solution to question 1
Answer: The script contains 165 / 100, and running it prints [1] 1.65.
Step by step
- Choose File → New File → R Script.
- Type the calculation on the first line.
165 / 100Output
[1] 1.653. Select the line, press Ctrl+Enter (Cmd+Enter on Mac), and read the Console: it prints 1.65.
4. Save with File → Save, name it my_first_script.R, and keep it in the project folder.
- Open the project again; run
getwd()andfile.exists("data/synthetic_ehr.csv").
Show solution to question 2
Answer: getwd() prints the path of the project folder, and file.exists() prints TRUE.
Step by step
- Open
R_Tutorial_Revision.Rprojso that R starts in the project folder. - Run the two checks.
getwd()getwd()prints the folder R is looking in, for example[1] "C:/Users/you/Documents/R_Tutorial_Revision"(your path will differ). Now the file check.
file.exists("data/synthetic_ehr.csv")Output
[1] TRUE4. TRUE means the relative path finds the file. If you get FALSE, reopen the project or unzip the bundle again.
- Explain the difference between
install.packages()andlibrary().
Show solution to question 3
Answer: install.packages() downloads a package onto the computer, usually once; library() loads an installed package into the current R session, and you do it in every new session.
Step by step
- Think of a phone app: installing puts it on the phone, and opening it makes it run.
install.packages("dplyr")needs the internet and changes what is stored on disk.library(dplyr)only makes the already-installed functions available now.
library(dplyr)- No output and no error means the package is installed and loaded.
- Create a new project called
practice_projectin a new directory, then rungetwd()inside it.
Show solution to question 4
Answer: After creating the project, getwd() prints a path that ends in practice_project.
Step by step
- Choose File → New Project → New Directory → New Project.
- Type
practice_projectas the directory name and use Browse to pick a location such as Documents. - Click Create Project. RStudio creates the folder and a
practice_project.Rprojfile and reopens in it. - In the Console, run
getwd().
getwd()- It prints a path such as
[1] "C:/Users/you/Documents/practice_project"(your path will differ). The path ending inpractice_projectconfirms the working directory is the new folder.
- Create a
.qmdfile with a#heading and one code chunk, and Render it to a report.
Show solution to question 5
Answer: A file my_report.qmd with the text below renders to my_report.html, showing the heading, the code and the output [1] 1.65.
Step by step
- Choose File → New File → Quarto Document, give it a title and click Create.
- Replace the body with this, then save as
my_report.qmdin the project folder.
# My report
```{r}
165 / 100
```- Click Render. RStudio runs the chunk and opens
my_report.html. - Check the page for the heading, the line
165 / 100and the printed1.65. If Render is missing, install Quarto (Step C).
- Name three packages in the tidyverse family and say which one this course uses for tables.
Show solution to question 6
Answer: For example dplyr, ggplot2 and tidyr; this course uses dplyr for tables.
Step by step
- The tidyverse is a family of packages that share a style:
dplyr(tables),ggplot2(plots),tidyr(reshaping).stringr,purrrandtibbleare others. - Check that two of them load.
library(dplyr)
library(ggplot2)- No error means both are available. The table tool is
dplyr.
- Locate a screenshot or copy the full error message if one of these steps fails.
Show solution to question 7
Answer: Copy the whole error text from the Console, from the first word to the last line, and take a screenshot if the problem is a click path; do not paraphrase it.
Step by step
- Find the red text in the Console (or the Render or Background Jobs tab for a report).
- Select all of it and copy it, or use your system screenshot tool (Windows: Win+Shift+S).
- Add what you ran just before it, such as
library(dplyr), and your R version, whichgetRversion()prints.
getRversion()Output
[1] '4.6.0'4. Send all of that to your mentor. The exact message usually tells them what is wrong, for example “there is no package called”.
Checkpoint
You can find the project, open a script, run a line, and locate the synthetic CSV without changing your working directory manually.