Intro to R Course
  • Prepare for the course
  • Copyright
  • Practical Sessions
  • Resources
  • Source Code
  • Report an issue
  1. Session 1
  2. Setting up your Workspace
  • Welcome
  • Session 1
    • Getting familiar with RStudio
    • Setting up your Workspace
    • Functions that make the work
  • Session 2
    • Data manipulation using the Tidyverse
    • Filtering rows
    • Creating variables
    • Grouping and summarising
  • Session 3
    • Intro to Data Cleaning
    • Variable Class
    • Recoding variables
    • Derived Variables & Export
  • Session 4
    • Counting cases
    • Crosstabulations and richer tables
    • Tables of things you cannot count
    • The whole table in one line

On this page

  • Part 4 · Your R Project and folder structure
    • What is an R Project?
    • Create the folder structure
    • Create your R Project
    • Start your script and add comments
  • Part 5 · Libraries
    • Installing and loading packages
    • Pacman for handling packages
  • Part 6 · File paths and importing data
    • The problem with file paths
    • The here() solution
    • Importing data
  • Exercise summary
  1. Session 1
  2. Setting up your Workspace

Setting up your Workspace

Session 1 practical exercises

Wow, that basics of R refresher was indeed useful!

Your supervisor has just confirmed you will be working with the unit’s surveillance data. Before they hand you the first dataset, you need to set up your working environment properly. In this unit — and throughout this course — everyone works inside an R Project. This is not a stylistic preference: it is what makes your work reproducible, portable, and shareable across different computers and colleagues.

When you begin a new project, these are the steps we recommend you to ALWAYS follow to set up the stage and have a nice, clean and functional working environment:

Part 4 · Your R Project and folder structure

What is an R Project?

An R Project is a folder that R treats as a self-contained workspace. When you open a project, RStudio automatically sets that folder as the starting point for all file paths. This means:

Always check the top-right corner Every time you open RStudio, glance at the top-right corner. If it says Project: (None), your project is not active. Always open RStudio by double-clicking your .Rproj file — not the .R script directly.

RStudio empty view (click to enlarge)

  • Your scripts work on any computer, not just yours
  • Colleagues can open the same project without changing a single path
  • You always know where R is looking for files

You will recognise an R Project by the .Rproj file inside its folder — and by the project name shown in the top-right corner of RStudio.

Create the folder structure

As the R Project is essentially a self-contained folder, you will need to first create a folder structure in your computer to meet the project needs. For this course, we provided you with it already - also to demonstrate the power of R Projects for sharing and reproducibility. If you haven’t downloaded the files yet go to this page

We recommend always creating the following subfolders:

IntroToRCourse/
├── data/
│   ├── raw/
│   └── clean/
├── scripts/
└── outputs/

Each folder has a specific role:

Folder Purpose
data/raw/ Original files, exactly as received — never modified
data/clean/ Processed versions you create in R
scripts/ Your R scripts
outputs/ Tables, plots, and reports you produce
TipWhy keep raw data untouched?

The raw/ folder holds your original files exactly as received. You never edit them — not in R, not in Excel, not at all. If something goes wrong during cleaning, the original data is always there to start again. This is one of the most important habits in reproducible data analysis.

Action — Once the folders exist, go back to RStudio and click the Files tab in the bottom-right panel. You should see your new folders listed there. If not, click “Refresh file listing”.

Create your R Project

Action — In RStudio, create a project through any of the following:

  • File → New Project → New Directory → New Project.
  • Create a project icon on the top-left menu
  • Project area at the top-right corner → Create new project

Action — Name your project IntroToRCourse. Choose the folder you downloaded for this course, that you can have store anywhere in your computer.

Action — Click Create Project. RStudio will reload and your project name should now appear in the top-right corner.

Action — Once the folders exist, go back to RStudio and click the Files tab in the bottom-right panel. You should see your project folders listed there.

Start your script and add comments

Now the project and folders are ready, lets open a new R Script to start fresh and let’s build it together. Initially, you will notice the script’s name is Unnamed1 which is a poor name, don’t you think? Let’s give it a decent name.

Action — Open a new script and save it first. Go to File → Save As or locate the Save button on the icon menu, navigate to your project’s scripts folder, and name it S1_practical.R. Every time you make some changes in your script, you’ll notice the script’s tab name turns red and gets an *. Don’t forget to save your script regularly, so your work doesn’t get lost.

Now it’s time you add some basic information about the script, like title, purpose, author, last date modified, etc. For this, you will learn how to use comments.

In a script, if a line begins with a hash # R understands anything behind as no-code text. The color of the text will change (typically to green, but it depends on your appearance customization). Use this feature to add at the beginning of the script some info:

# Title: my first script
# Function: Learn the basics of working in R
# Author: your_name
# Last modified: 8th Sept 2026

Comments are an essential part of every script. They serve several purposes: creating sections, explaining what is being done, leave comments for you or others to understand, have a clean code, and so on. We will use them from now on for everything we do.

Part 5 · Libraries

R comes with a set of built-in functions — but much of what makes R powerful for epidemiology lives in packages: collections of functions written by the R community and freely available to install.

Before you can use a package, two things need to happen:

  1. Install it — downloads the package to your computer (once per machine)
  2. Load it — makes the package available in your current session (every time you open R)

Installing and loading packages

The classic way to install a package is:

This downloads the package from CRAN (the official R package repository) to your computer. You only need to do this once per machine — after that, the package lives on your computer and just needs to be loaded.

To update an already installed package to its latest version:

update.packages("pacman")

Installing/Updating is something that happens in your computer but not in your R Session. An installed package also needs to be loaded in order to become active and use the new functions provided

NoteInstall once, load every session

A common source of confusion: install.packages() and library() do very different things. Installing is like buying a book and putting it on your shelf. Loading is like taking it off the shelf to read it. You only buy it once, but you need to pick it up every time you want to use it.

The classic way to load a package is:

library(pacman)

This works perfectly well, but it has a limitation: if the package is not installed, it throws an error and stops. When you are sharing scripts with colleagues who may not have the same packages, this becomes a problem. Also, you need to remember three functions in order to keep your packages always ready, and we like efficiency.

We can do better.

Pacman for handling packages

The pacman library was developed to handle libraries in R more easily. Its main function, p_load(), checks whether each package is installed — if it is, it loads it; if it is not, it installs it first and then loads it. One line, any number of packages, no errors from missing installations.

pacman::p_load(rio, here, tidyverse)

Notice this little paradox: we need to install and load a package for installing/updating/loading packages. There is nothing we can do with it. The very first time you install pacman in your computer you will need to use the basic install.packages() and library() functions. Once installed, we have a little trick under the sleeve called package::function()

Tippackage::function() syntax

Notice we wrote pacman::p_load() instead of loading pacman first with library(pacman). The :: syntax lets you call a function from a package without loading the whole package — useful for one-off calls or to make clear which package a function comes from. You will see this throughout the course.

You should have all the needed libraries for the course already installed, as stated in the instructions you received beforehand. You can find them in this page, copy the code and install all libraries.

Action — In your S1_practical.R script, add a libraries section after the first comments, and load the following packages using pacman::p_load():

pacman::p_load(
  pacman,     # for managing libraries 
  rio,        # for importing any file format
  here        # for route management within R Projects
)

Run it and watch the Console. The first time may take a moment if any packages need downloading.

What does install.packages() actually do?

Part 6 · File paths and importing data

The problem with file paths

When R reads a file, it needs to know exactly where that file lives on your computer. The naive approach is to write the full path:

read.csv("C:/Users/yourname/Documents/IntroToRCourse/data/raw/imd_S1.xlsx")

This works — but only on your computer. The moment a colleague opens the same script, or you move the project to a different folder, the path breaks. This is a fragile way to work.

The here() solution

The here package solves this by building file paths relative to your R Project root — the folder where your .Rproj file lives. Instead of writing the full path, you write:

Action — In your script, call here::here() with no arguments and run it

You should see the full path to your project folder printed in the Console. That is the root here() is working from. The way here() works is by passing quoted folder names as arguments (separated by comma) to navigate from the root folder to the file or folder of your interest

You have a file (imd_S1.xlsx) located in the raw data folder. Let’s navigate to it:

Action — Build a path to the data file:

here::here("data", "raw", "IMD_S1.xlsx")

Run this line. R will print the full path — but it will not read the file yet. You are just constructing the address.

What type of output is here() producing

Importing data

Now you will read the file for the first time.

Action — Load your data using its path and the import() function. Don’t forget to assign it to a new object named imd_raw

# Load raw data
imd_raw <- rio::import(here::here("data", "raw", "IMD_S1.xlsx"))

Two things are happening here:

  • here::here() builds the path to the file
  • rio::import() reads the file and stores it as an object called imd_raw in your Environment

Notice how we used one function to crate an output (a computer path) that is the required argument for the other function - a nested approach.

rio::import() supports many file formats and automatically detects the type from the file extension. When importing an Excel workbook with multiple sheets, don’t forget to specify the sheet if your data is not on the first one: imd_raw <- rio::import(here::here("data", "raw", "IMD_S1.xlsx"), which = "Cases")).

Action — Check your Environment panel — you should see imd_raw appear there. What is different with this object compared with the previous ones?


Exercise summary

Congrats! You have successfully created your basic R Infrastructure: folders, R Project, Libraries and Data Import

Every time you start a new task in real life, you will need a Project to store everything and work in a reproducible way, especially in collaborative settings. Projects will also be splitted into multiple scripts, with each one fulfilling one specific task (e.g., data cleaning, exploratory analysis, table production, etc.). All of them will start with some information on top, then libraries and data needed for the specific tasks. In no time you will find yourself reproducing these without even thinking

This is what you practiced and learned:

R Project A self-contained workspace anchored to a folder with a .Rproj file
Folder structure data/raw, data/clean, scripts, outputs — each with a clear role
install.packages() Downloads a package to your computer — once per machine
update.packages() Updates an installed package to its most recent version — periodically
library() Loads a package for your current session — every time you open R
pacman::p_load() Installs or updates (if needed) AND loads a package
here::here() Builds portable file paths from your project root
rio::import() Reads data files into R as objects

Getting familiar with RStudio
Functions that make the work
Source Code
---
title: "Setting up your Workspace"
subtitle: "Session 1 practical exercises"
format:
  html:
    code-fold: false
---

```{r}
#| include: false
library(webexercises)
library(rio)
library(here)
```

Wow, that basics of R refresher was indeed useful!

Your supervisor has just confirmed you will be working with the unit's surveillance data. Before they hand you the first dataset, you need to set up your working environment properly. In this unit — and throughout this course — everyone works inside an **R Project**. This is not a stylistic preference: it is what makes your work reproducible, portable, and shareable across different computers and colleagues.

When you begin a new project, these are the steps we recommend you to ALWAYS follow to set up the stage and have a nice, clean and functional working environment:

## Part 4 · Your R Project and folder structure

### What is an R Project?

An R Project is a folder that R treats as a self-contained workspace. When you open a project, RStudio automatically sets that folder as the starting point for all file paths. This means:

::: column-margin
**Always check the top-right corner** Every time you open RStudio, glance at the top-right corner. If it says **Project: (None)**, your project is not active. Always open RStudio by double-clicking your `.Rproj` file — not the `.R` script directly.

RStudio empty view (click to enlarge)

![](/images/exercises/S1E2_1_project.png){.lightbox}
:::

-   Your scripts work on any computer, not just yours
-   Colleagues can open the same project without changing a single path
-   You always know where R is looking for files

You will recognise an R Project by the `.Rproj` file inside its folder — and by the project name shown in the **top-right corner of RStudio**.

### Create the folder structure

As the R Project is essentially a self-contained folder, you will need to first create a folder structure in your computer to meet the project needs. For this course, we provided you with it already - also to demonstrate the power of R Projects for sharing and reproducibility. If you haven't downloaded the files yet go to [this page](/scripts/preparation.qmd)

We recommend always creating the following subfolders:

```         
IntroToRCourse/
├── data/
│   ├── raw/
│   └── clean/
├── scripts/
└── outputs/
```

Each folder has a specific role:

| Folder        | Purpose                                              |
|---------------|------------------------------------------------------|
| `data/raw/`   | Original files, exactly as received — never modified |
| `data/clean/` | Processed versions you create in R                   |
| `scripts/`    | Your R scripts                                       |
| `outputs/`    | Tables, plots, and reports you produce               |

::: callout-tip
### Why keep raw data untouched?

The `raw/` folder holds your original files exactly as received. You never edit them — not in R, not in Excel, not at all. If something goes wrong during cleaning, the original data is always there to start again. This is one of the most important habits in reproducible data analysis.
:::

**Action** — Once the folders exist, go back to RStudio and click the **Files** tab in the bottom-right panel. You should see your new folders listed there. If not, click "Refresh file listing".

![](/images/exercises/S1E2_2_refresh.png)

### Create your R Project

**Action** — In RStudio, create a project through any of the following:

-   File → New Project → New Directory → New Project.
-   Create a project icon on the top-left menu
-   Project area at the top-right corner → Create new project

**Action** — Name your project `IntroToRCourse`. Choose the folder you downloaded for this course, that you can have store anywhere in your computer.

**Action** — Click **Create Project**. RStudio will reload and your project name should now appear in the top-right corner.

**Action** — Once the folders exist, go back to RStudio and click the **Files** tab in the bottom-right panel. You should see your project folders listed there.

### Start your script and add comments

Now the project and folders are ready, lets open a new R Script to start fresh and let's build it together. Initially, you will notice the script's name is `Unnamed1` which is a poor name, don't you think? Let's give it a decent name.

**Action** — Open a new script and save it first. Go to **File → Save As** or locate the Save button on the icon menu, navigate to your project's `scripts` folder, and name it `S1_practical.R`. Every time you make some changes in your script, you'll notice the script's tab name turns red and gets an \*. Don't forget to save your script regularly, so your work doesn't get lost.

Now it's time you add some basic information about the script, like title, purpose, author, last date modified, etc. For this, you will learn how to use **comments**.

In a script, if a line begins with a hash `#` R understands anything behind as no-code text. The color of the text will change (typically to green, but it depends on your appearance customization). Use this feature to add at the beginning of the script some info:

```{r}
# Title: my first script
# Function: Learn the basics of working in R
# Author: your_name
# Last modified: 8th Sept 2026
```

**Comments** are an essential part of every script. They serve several purposes: creating sections, explaining what is being done, leave comments for you or others to understand, have a clean code, and so on. We will use them from now on for everything we do.

## Part 5 · Libraries

R comes with a set of built-in functions — but much of what makes R powerful for epidemiology lives in **packages**: collections of functions written by the R community and freely available to install.

Before you can use a package, two things need to happen:

1.  **Install** it — downloads the package to your computer (once per machine)
2.  **Load** it — makes the package available in your current session (every time you open R)

### Installing and loading packages

The classic way to install a package is:

```{r}
#| eval: false
#| execute: false
#| include: false
install.packages("pacman")
```

This downloads the package from CRAN (the official R package repository) to your computer. You only need to do this once per machine — after that, the package lives on your computer and just needs to be loaded.

To update an already installed package to its latest version:

```{r}
#| eval: false
update.packages("pacman")
```

Installing/Updating is something that happens in your computer but not in your R Session. An installed package also needs to be `loaded` in order to become active and use the new functions provided

:::: column-margin
::: callout-note
### Install once, load every session

A common source of confusion: `install.packages()` and `library()` do very different things. Installing is like buying a book and putting it on your shelf. Loading is like taking it off the shelf to read it. You only buy it once, but you need to pick it up every time you want to use it.
:::
::::

The classic way to load a package is:

```{r}
#| eval: false
library(pacman)
```

This works perfectly well, but it has a limitation: if the package is not installed, it throws an error and stops. When you are sharing scripts with colleagues who may not have the same packages, this becomes a problem. Also, you need to remember three functions in order to keep your packages always ready, and we like efficiency.

We can do better.

### Pacman for handling packages

The `pacman` library was developed to handle libraries in R more easily. Its main function, `p_load()`, checks whether each package is installed — if it is, it loads it; if it is not, it installs it first and then loads it. One line, any number of packages, no errors from missing installations.

```{r}
#| execute: false
pacman::p_load(rio, here, tidyverse)
```

Notice this little **paradox**: we need to install and load a package for installing/updating/loading packages. There is nothing we can do with it. The very first time you install `pacman` in your computer you will need to use the basic `install.packages()` and `library()` functions. Once installed, we have a little trick under the sleeve called `package::function()`

::: callout-tip
### `package::function()` syntax

Notice we wrote `pacman::p_load()` instead of loading `pacman` first with `library(pacman)`. The `::` syntax lets you call a function from a package without loading the whole package — useful for one-off calls or to make clear which package a function comes from. You will see this throughout the course.
:::

You should have all the needed libraries for the course already installed, as stated in the instructions you received beforehand. You can find them in this page, copy the code and install all libraries.

**Action** — In your `S1_practical.R` script, add a libraries section after the first comments, and load the following packages using `pacman::p_load()`:

```{r}
#| eval: false
pacman::p_load(
  pacman,     # for managing libraries 
  rio,        # for importing any file format
  here        # for route management within R Projects
)
```

Run it and watch the Console. The first time may take a moment if any packages need downloading.

```{r}
#| echo: false
opts_lib <- c(
  "It installs the package and makes it available permanently, no need to load it again",
  answer = "It installs the package to your computer, but you still need to load it at the start of every R session",
  "It loads the package for this session only, and uninstalls it when you close R",
  "It checks if the package is up to date and updates it if necessary"
)
```

**What does `install.packages()` actually do?** `r longmcq(opts_lib)`

## Part 6 · File paths and importing data

### The problem with file paths

When R reads a file, it needs to know exactly where that file lives on your computer. The naive approach is to write the full path:

```{r}
#| eval: false
read.csv("C:/Users/yourname/Documents/IntroToRCourse/data/raw/imd_S1.xlsx")
```

This works — but only on your computer. The moment a colleague opens the same script, or you move the project to a different folder, the path breaks. This is a fragile way to work.

### The `here()` solution

The `here` package solves this by building file paths relative to your R Project root — the folder where your `.Rproj` file lives. Instead of writing the full path, you write:

**Action** — In your script, call `here::here()` with no arguments and run it

You should see the full path to your project folder printed in the Console. That is the root `here()` is working from. The way `here()` works is by passing quoted folder names as arguments (separated by comma) to navigate from the root folder to the file or folder of your interest

You have a file (`imd_S1.xlsx`) located in the raw data folder. Let's navigate to it:

**Action** — Build a path to the data file:

```{r}
#| eval: false
here::here("data", "raw", "IMD_S1.xlsx")
```

Run this line. R will print the full path — but it will not read the file yet. You are just constructing the address.

```{r}
#| echo: false
opts_here <- c(
  "A connection to the file, which allows R to start reading its contents ",
  answer = "A file path stored as a text string, which can be passed directly to other functions",
  "A special path object that automatically updates if you move your project to a different folder"
)
```

**What type of output is here() producing** `r longmcq(opts_here)`

### Importing data

Now you will read the file for the first time.

**Action** — Load your data using its path and the `import()` function. Don't forget to assign it to a new object named `imd_raw`

```{r}
#| eval: false
# Load raw data
imd_raw <- rio::import(here::here("data", "raw", "IMD_S1.xlsx"))
```

Two things are happening here:

-   `here::here()` builds the path to the file
-   `rio::import()` reads the file and stores it as an object called `imd_raw` in your Environment

Notice how we used one function to crate an output (a computer path) that is the required argument for the other function - a nested approach.

`rio::import()` supports many file formats and automatically detects the type from the file extension. When importing an Excel workbook with multiple sheets, don't forget to specify the sheet if your data is not on the first one: `imd_raw <- rio::import(here::here("data", "raw", "IMD_S1.xlsx"), which = "Cases"`)).

**Action** — Check your Environment panel — you should see `imd_raw` appear there. What is different with this object compared with the previous ones?

------------------------------------------------------------------------

## Exercise summary

**Congrats! You have successfully created your basic R Infrastructure: folders, R Project, Libraries and Data Import**

Every time you start a new task in real life, you will need a Project to store everything and work in a reproducible way, especially in collaborative settings. Projects will also be splitted into multiple scripts, with each one fulfilling one specific task (e.g., data cleaning, exploratory analysis, table production, etc.). All of them will start with some information on top, then libraries and data needed for the specific tasks. In no time you will find yourself reproducing these without even thinking

This is what you practiced and learned:

|  |  |
|:---|:---|
| **R Project** | A self-contained workspace anchored to a folder with a `.Rproj` file |
| **Folder structure** | `data/raw`, `data/clean`, `scripts`, `outputs` — each with a clear role |
| **`install.packages()`** | Downloads a package to your computer — once per machine |
| **`update.packages()`** | Updates an installed package to its most recent version — periodically |
| **`library()`** | Loads a package for your current session — every time you open R |
| **`pacman::p_load()`** | Installs or updates (if needed) AND loads a package |
| **`here::here()`** | Builds portable file paths from your project root |
| **`rio::import()`** | Reads data files into R as objects |

------------------------------------------------------------------------

```{=html}
<script>
document.addEventListener("DOMContentLoaded", function() {
  var radiogroups = document.getElementsByClassName("webex-radiogroup");
  for (var i = 0; i < radiogroups.length; i++) {
    radiogroups[i].onchange = radiogroups_func;
  }
});
</script>
```

© 2026 – Intro to R Course