read_csv("file.csv") helps us to import files into R
read.csvlibrary(readr)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.2.1 ✔ purrr 1.2.2
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ ggplot2 4.0.3 ✔ tibble 3.3.1
## ✔ lubridate 1.9.5 ✔ tidyr 1.3.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Option 1 (not best): Use the full file path (workbench example)
# read_csv(file = "/home/graceyin/Lecture Materials/testdata.csv")
# Option 2 (best!): Use only a relative path
# read_csv(file = "testdata.csv")
# Check your current working directory
getwd()
## [1] "/home/graceyin/Lecture Materials"
# Option 3 (not best): Choose the file manually
# Not recommended for reproducible code
# read_csv(file = file.choose())
Modifying the col_types argument By default, read_csv() guesses the column types:
read_csv(file = "testdata.csv", col_types = NULL)
## Rows: 4 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): name, age, food
## dbl (1): id
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## # A tibble: 4 × 4
## id name age food
## <dbl> <chr> <chr> <chr>
## 1 1 sandra 19 pizza
## 2 2 erick na ice cream
## 3 3 luke 23 None
## 4 4 aaron <NA> pasta
But we can also tell R what each column type should be:
read_csv(
file = "testdata.csv",
col_types = "icic")
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
## dat <- vroom(...)
## problems(dat)
## # A tibble: 4 × 4
## id name age food
## <int> <chr> <int> <chr>
## 1 1 sandra 19 pizza
## 2 2 erick NA ice cream
## 3 3 luke 23 None
## 4 4 aaron NA pasta
Modifying the na argument
By default, read_csv() treats empty cells and “NA” as missing values:
read_csv(file = "testdata.csv", na = c("", "NA"))
## Rows: 4 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): name, age, food
## dbl (1): id
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## # A tibble: 4 × 4
## id name age food
## <dbl> <chr> <chr> <chr>
## 1 1 sandra 19 pizza
## 2 2 erick na ice cream
## 3 3 luke 23 None
## 4 4 aaron <NA> pasta
But we can also specify other values that should be treated as missing:
read_csv(
file = "testdata.csv",
col_types = "icic",
na = c("", "NA", "na", "None"))
## # A tibble: 4 × 4
## id name age food
## <int> <chr> <int> <chr>
## 1 1 sandra 19 pizza
## 2 2 erick NA ice cream
## 3 3 luke 23 <NA>
## 4 4 aaron NA pasta
Modifying the skip argument
By default, read_csv() starts reading from the first row:
library(haven)
read_csv(file = "testdata.csv", skip = 0)
## Rows: 4 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): name, age, food
## dbl (1): id
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## # A tibble: 4 × 4
## id name age food
## <dbl> <chr> <chr> <chr>
## 1 1 sandra 19 pizza
## 2 2 erick na ice cream
## 3 3 luke 23 None
## 4 4 aaron <NA> pasta
But we can tell R to skip rows at the beginning of the file:
read_csv(file = "testdata.csv", skip = 2)
## Rows: 2 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): erick, ice cream
## dbl (2): 2, na
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## # A tibble: 2 × 4
## `2` erick na `ice cream`
## <dbl> <chr> <dbl> <chr>
## 1 3 luke 23 None
## 2 4 aaron NA pasta
Use skip when the CSV file contains extra or messy rows
at the top.
Takeaways from using read_csv()
Importing files correctly is important because small mistakes during import can cause problems in later analyses.
When data are not imported correctly, check the arguments in
read_csv() first: + file: Specifies the file
path. + col_types: Specifies the column types. +
na: Specifies which values should be treated as missing. +
col_names: Determines whether the first row contains column
names. + skip: Specifies how many rows to skip at the
beginning of the file.
read_csv("testdata.csv")getwd()SPSS
Use read_sav() from the haven package to
import SPSS files (.sav):
read_sav(file = system.file("examples", "iris.sav",
package = "haven"))
## # A tibble: 150 × 5
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## <dbl> <dbl> <dbl> <dbl> <dbl+lbl>
## 1 5.1 3.5 1.4 0.2 1 [setosa]
## 2 4.9 3 1.4 0.2 1 [setosa]
## 3 4.7 3.2 1.3 0.2 1 [setosa]
## 4 4.6 3.1 1.5 0.2 1 [setosa]
## 5 5 3.6 1.4 0.2 1 [setosa]
## 6 5.4 3.9 1.7 0.4 1 [setosa]
## 7 4.6 3.4 1.4 0.3 1 [setosa]
## 8 5 3.4 1.5 0.2 1 [setosa]
## 9 4.4 2.9 1.4 0.2 1 [setosa]
## 10 4.9 3.1 1.5 0.1 1 [setosa]
## # ℹ 140 more rows
Stata
Use read_dta() from the haven package to
import Stata files (.dta):
read_dta(file = system.file("examples", "iris.dta",
package = "haven"))
## # A tibble: 150 × 5
## sepallength sepalwidth petallength petalwidth species
## <dbl> <dbl> <dbl> <dbl> <chr>
## 1 5.10 3.5 1.40 0.200 setosa
## 2 4.90 3 1.40 0.200 setosa
## 3 4.70 3.20 1.30 0.200 setosa
## 4 4.60 3.10 1.5 0.200 setosa
## 5 5 3.60 1.40 0.200 setosa
## 6 5.40 3.90 1.70 0.400 setosa
## 7 4.60 3.40 1.40 0.300 setosa
## 8 5 3.40 1.5 0.200 setosa
## 9 4.40 2.90 1.40 0.200 setosa
## 10 4.90 3.10 1.5 0.100 setosa
## # ℹ 140 more rows
write_csv()# import
test <- read_csv("testdata.csv", col_types = ("icic"), na = c("", "NA", "na", "None"))
# then you write your data analysis and visualization code etc.
# once done, export
write_csv(test, file = "testdata_cleaned.csv")
inner_join()left_join()right_join()full_join()semi_join()anti_join()by = "id" means matching rows using the id
column.| Function | What it does | Key point |
|---|---|---|
inner_join() |
Keeps observations matching in both data frames | Drops unmatched rows |
left_join() |
Keeps all observations from the left data frame | Unmatched right values become NA |
right_join() |
Keeps all observations from the right data frame | Unmatched left values become NA |
full_join() |
Keeps observations from both data frames | Includes unmatched observations |
library(tidyverse)
# Example data frames
x <- tibble(
id = c(1, 2, 3),
name = c("Ana", "Ben", "Cleo")
)
y <- tibble(
id = c(2, 3, 4),
score = c(80, 90, 75)
)
# INNER JOIN - only matching IDs
inner_join(x, y, by = "id")
## # A tibble: 2 × 3
## id name score
## <dbl> <chr> <dbl>
## 1 2 Ben 80
## 2 3 Cleo 90
# Keeps id 2 and 3
# Same using pipe
x |>
inner_join(y, by = "id")
## # A tibble: 2 × 3
## id name score
## <dbl> <chr> <dbl>
## 1 2 Ben 80
## 2 3 Cleo 90
# LEFT JOIN - keeps all rows in x
left_join(x, y, by = "id")
## # A tibble: 3 × 3
## id name score
## <dbl> <chr> <dbl>
## 1 1 Ana NA
## 2 2 Ben 80
## 3 3 Cleo 90
# id 1 has NA for score
# RIGHT JOIN - keeps all rows in y
right_join(x, y, by = "id")
## # A tibble: 3 × 3
## id name score
## <dbl> <chr> <dbl>
## 1 2 Ben 80
## 2 3 Cleo 90
## 3 4 <NA> 75
# id 4 has NA for name
# FULL JOIN - keeps all rows from x and y
full_join(x, y, by = "id")
## # A tibble: 4 × 3
## id name score
## <dbl> <chr> <dbl>
## 1 1 Ana NA
## 2 2 Ben 80
## 3 3 Cleo 90
## 4 4 <NA> 75
# Keeps id 1, 2, 3, 4
# If key variable names are DIFFERENT
x2 <- tibble(
student_id = c(1, 2, 3),
name = c("Ana", "Ben", "Cleo")
)
inner_join(x2, y, by = c("student_id" = "id"))
## # A tibble: 2 × 3
## student_id name score
## <dbl> <chr> <dbl>
## 1 2 Ben 80
## 2 3 Cleo 90
# Matches student_id from x2 with id from y
| Function | What it does | Result |
|---|---|---|
semi_join() |
Keeps rows in x that have matches in y | Columns from x only |
anti_join() |
Keeps rows in x that do not have matches in y | Columns from x only |
# SEMI JOIN
semi_join(x, y, by = "id")
## # A tibble: 2 × 2
## id name
## <dbl> <chr>
## 1 2 Ben
## 2 3 Cleo
# Keeps id 2 and 3 from x
# Does NOT add score from y
# ANTI JOIN
anti_join(x, y, by = "id")
## # A tibble: 1 × 2
## id name
## <dbl> <chr>
## 1 1 Ana
# Keeps id 1 from x
# Does NOT add score from y
inner_join() is useful when we only want observations
present in both data frames.left_join() is useful when we want to preserve all
observations from the original data.semi_join() checks whether matching observations exist
without adding columns.anti_join() helps identify unmatched observations.# Check duplicate IDs
x |>
count(id) |>
filter(n > 1)
## # A tibble: 0 × 2
## # ℹ 2 variables: id <dbl>, n <int>
# Check number of rows before and after join
nrow(x)
## [1] 3
joined_data <- inner_join(x, y, by = "id")
nrow(joined_data)
## [1] 2
# Join vote-level and case-level data
combined_votes <- current_justices |>
inner_join(
selected_issueArea |>
select(caseId, issueArea),
by = "caseId"
)
# Matching variable = caseId
# Added variable = issueArea
# Keeps votes with matching cases only
| Question | Answer |
|---|---|
| What is a key? | Variable(s) used to match rows across data frames |
inner_join() vs
left_join()? |
Inner keeps matches only; left keeps all rows from x |
semi_join() vs
inner_join()? |
Semi filters rows only; inner also adds columns |
anti_join()? |
Finds rows in x without matches in y |
What does by = "id" mean? |
Use id to match observations |
| Why check duplicate keys? | Duplicate matches can multiply observations |
lubridate is a package that helps us work with dates
and times.| Function | What it does | Example |
|---|---|---|
ymd() |
Converts Year-Month-Day strings to dates | ymd("2017-01-31") |
mdy() |
Converts Month-Day-Year strings to dates | mdy("01/31/2017") |
dmy() |
Converts Day-Month-Year strings to dates | dmy("31-Jan-2017") |
ymd_hms() |
Converts strings containing date and time | ymd_hms("2017-01-31 20:11:59") |
make_datetime() |
Constructs datetime from separate variables | make_datetime(year, month, day, hour, minute) |
year() |
Extracts year | year(date) |
month() |
Extracts month | month(date) |
mday() |
Extracts day of month | mday(date) |
yday() |
Extracts day of year | yday(date) |
wday() |
Extracts day of week | wday(date) |
floor_date() |
Rounds date down | floor_date(date, "month") |
ceiling_date() |
Rounds date up | ceiling_date(date, "month") |
round_date() |
Rounds to nearest specified unit | round_date(date, "hour") |
today() |
Returns current date | today() |
with_tz() |
Displays same instant in another time zone | with_tz(dt, tzone = "America/Chicago") |
force_tz() |
Assigns a time zone without changing clock time | force_tz(dt, "America/Chicago") |
ymd: Year-Month-Daymdy: Month-Day-Yeardmy: Day-Month-Yearlibrary(lubridate)
# Year-Month-Day
ymd("2017-01-31")
## [1] "2017-01-31"
# Month-Day-Year
mdy("January 31st, 2017")
## [1] "2017-01-31"
mdy("01/31/2017")
## [1] "2017-01-31"
# Day-Month-Year
dmy("31-Jan-2017")
## [1] "2017-01-31"
# Date + Time
ymd_hms("2017-01-31 20:11:59")
## [1] "2017-01-31 20:11:59 UTC"
make_datetime() when the components are stored in
separate columns.library(tidyverse)
library(nycflights13)
# Create datetime variable
flights |>
select(year, month, day, hour, minute) |>
mutate(
departure = make_datetime(
year, month, day, hour, minute
)
)
month() returns 1–12 by default.wday() returns 1–7 by default, with Sunday = 1.datetime <- ymd_hms("2025-10-22 12:30:33")
year(datetime) # 2025
## [1] 2025
month(datetime) # 10 (October)
## [1] 10
mday(datetime) # 22
## [1] 22
yday(datetime) # 295
## [1] 295
wday(datetime) # 4 (Wednesday)
## [1] 4
| Function | What it does | Example |
|---|---|---|
floor_date() |
Round DOWN | October 22 -> October 1 |
ceiling_date() |
Round UP | October 22 -> November 1 |
round_date() |
Round to nearest unit | 12:45 -> 13:00 |
dt <- ymd_hms("2025-10-22 12:45:00")
# Round down
floor_date(dt, "day")
## [1] "2025-10-22 UTC"
floor_date(dt, "month")
## [1] "2025-10-01 UTC"
# Round up
ceiling_date(dt, "day")
## [1] "2025-10-23 UTC"
ceiling_date(dt, "month")
## [1] "2025-11-01 UTC"
# Round to nearest hour
round_date(dt, "hour")
## [1] "2025-10-22 13:00:00 UTC"
# Current date
today()
## [1] "2026-11-28"
# Calculate time difference
age <- today() - ymd("2001-10-22")
age
## Time difference of 9168 days
# Convert time span into duration
as.duration(age)
## [1] "792115200s (~25.1 years)"
with_tz() converts the display to another time zone
while keeping the same instant.force_tz() changes the assigned time zone while keeping
the clock time.greenwich <- ymd_hms("2025-10-22 06:45:00")
# Same instant in Chicago time
with_tz(
greenwich,
tzone = "America/Chicago"
)
## [1] "2025-10-22 01:45:00 CDT"
# Assign Chicago timezone without shifting clock time
force_tz(
greenwich,
"America/Chicago"
)
## [1] "2025-10-22 06:45:00 CDT"
# Extract month from decision date
oral_argument <- oral_argument |>
mutate(
decision_month = month(
mdy(dateDecision)
)
)
# Count decisions by month and term
monthlyDecisions_byTerm <- oral_argument |>
group_by(term, decision_month) |>
summarize(
n_decision = n(),
.groups = "drop"
)
# Order months from October to September
monthlyDecisions_byTerm <- monthlyDecisions_byTerm |>
mutate(
decision_month = factor(
decision_month,
levels = c(10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9),
labels = c(
"October", "November", "December",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September"
)
)
)
| Question | Answer |
|---|---|
ymd() vs mdy()? |
Depends on the original date string order |
What does month() return? |
Month number from 1 to 12 by default |
What does make_datetime() do? |
Builds a datetime from separate components |
floor_date() vs
ceiling_date()? |
Round down vs round up |
with_tz() vs force_tz()? |
Same instant vs same clock time |
Why use factor() after extracting
months? |
To control the order on graphs |
| Base R | Tidyverse |
|---|---|
| Core R language | Collection of R packages |
df[df$age > 20, ] |
filter(df, age > 20) |
df["age"] |
select(df, age) |
df[["age"]] |
pull(df, age) |
mean(df$score) |
summarize(df, avg = mean(score)) |
| Type | Meaning | Example |
|---|---|---|
| Numeric / Double | Numbers, usually stored as double | 3.14, 2 |
| Integer | Whole-number type | 2L, 100L |
| Character | Text | "hello" |
| Logical | TRUE or FALSE | TRUE, FALSE |
| Factor | Categorical values with levels | "Low", "High" |
# Numeric / double
x <- 3.14
class(x)
## [1] "numeric"
# Integer
x <- 3L
class(x)
## [1] "integer"
# Character
x <- "hello"
class(x)
## [1] "character"
# Logical
x <- TRUE
class(x)
## [1] "logical"
# Factor
x <- factor(c("low", "medium", "high"))
class(x)
## [1] "factor"
levels(x)
## [1] "high" "low" "medium"
| Structure | Dimension | Mixed Data Types? | Example |
|---|---|---|---|
| Vector | 1D | No | c(1, 2, 3) |
| Matrix | 2D | No | matrix(1:6, nrow = 2) |
| Data Frame | 2D | Yes, across columns | data.frame(...) |
| List | Flexible | Yes | list(...) |
# VECTOR
v <- c(1, 2, 3)
# MATRIX
m <- matrix(1:6, nrow = 2)
# DATA FRAME
df <- data.frame(
name = c("Ana", "Ben"),
age = c(20, 21)
)
# LIST
l <- list(
numbers = 1:3,
name = c("Ana", "Ben")
)
# Inspect objects
class(v)
## [1] "numeric"
str(v)
## num [1:3] 1 2 3
class(m)
## [1] "matrix" "array"
str(m)
## int [1:2, 1:3] 1 2 3 4 5 6
class(df)
## [1] "data.frame"
str(df)
## 'data.frame': 2 obs. of 2 variables:
## $ name: chr "Ana" "Ben"
## $ age : num 20 21
class(l)
## [1] "list"
str(l)
## List of 2
## $ numbers: int [1:3] 1 2 3
## $ name : chr [1:2] "Ana" "Ben"
[ ] to select elements.v <- c(10, 20, 30, 40)
v[2] # Second element: 20
## [1] 20
v[c(1, 3)] # First and third elements
## [1] 10 30
v[-1] # All except first element
## [1] 20 30 40
v[v > 25] # Elements greater than 25
## [1] 30 40
# Check vector
class(v)
## [1] "numeric"
length(v)
## [1] 4
[row, column] to select elements.m <- matrix(
1:9,
nrow = 3,
byrow = TRUE
)
m[1, 2] # Row 1, column 2
## [1] 2
m[, 3] # Entire third column
## [1] 3 6 9
m[2, ] # Entire second row
## [1] 4 5 6
m[1:2, 2:3] # Rows 1-2, columns 2-3
## [,1] [,2]
## [1,] 2 3
## [2,] 5 6
m[, c(1, 3)] # Columns 1 and 3
## [,1] [,2]
## [1,] 1 3
## [2,] 4 6
## [3,] 7 9
[ ] returns a sublist.[[ ]] extracts the actual contents of an element.$ extracts an element by name.my_list <- list(
a = c(20, 30, 40),
b = c("hello", "ciao"),
c = TRUE
)
my_list[1] # Returns a LIST
## $a
## [1] 20 30 40
my_list[[1]] # Returns VECTOR: 20, 30, 40
## [1] 20 30 40
my_list[[1]][1] # First value: 20
## [1] 20
my_list[2] # Returns second element as LIST
## $b
## [1] "hello" "ciao"
my_list["b"] # Returns element b as LIST
## $b
## [1] "hello" "ciao"
my_list$b # Extract contents of b
## [1] "hello" "ciao"
my_list[["c"]] # TRUE
## [1] TRUE
# Important:
# [ ] returns a list
# [[ ]] extracts contents
[row, column] for subsetting.df <- data.frame(
name = c("Alex", "Betty", "Chad", "J"),
age = c(20, 21, 22, 23)
)
# Select rows and columns
df[1, ] # First row
## name age
## 1 Alex 20
df[, 1] # First column
## [1] "Alex" "Betty" "Chad" "J"
df[, "name"] # Column by name
## [1] "Alex" "Betty" "Chad" "J"
df$name # Extract name vector
## [1] "Alex" "Betty" "Chad" "J"
df[["name"]] # Extract name vector
## [1] "Alex" "Betty" "Chad" "J"
df[1, 2] # Single value
## [1] 20
df[2:3, "name"] # Rows 2-3 from name
## [1] "Betty" "Chad"
# Filter rows
df[df$age > 20, ]
## name age
## 2 Betty 21
## 3 Chad 22
## 4 J 23
df[df$name == "J", ]
## name age
## 4 J 23
df[df$age == max(df$age), ]
## name age
## 4 J 23
| Goal | Base R | Tidyverse |
|---|---|---|
| Keep a column as a data frame | df["age"] |
select(df, age) |
| Extract a column as a vector | df[["age"]] |
pull(df, age) |
| Filter rows | df[df$age > 20, ] |
filter(df, age > 20) |
# Base R - DATA FRAME
df["age"]
## age
## 1 20
## 2 21
## 3 22
## 4 23
# Tidyverse - DATA FRAME
df |>
select(age)
## age
## 1 20
## 2 21
## 3 22
## 4 23
# Base R - VECTOR
df[["age"]]
## [1] 20 21 22 23
# Tidyverse - VECTOR
df |>
pull(age)
## [1] 20 21 22 23
# Base R - FILTER
df[df$age > 20, ]
## name age
## 2 Betty 21
## 3 Chad 22
## 4 J 23
# Tidyverse - FILTER
df |>
filter(age > 20)
## name age
## 1 Betty 21
## 2 Chad 22
## 3 J 23
# Add 100 to each element
x <- 1:10
x + 100
## [1] 101 102 103 104 105 106 107 108 109 110
# Shorter vector repeated
x1 <- c(1, 2)
x2 <- 1:10
x1 + x2
## [1] 2 4 4 6 6 8 8 10 10 12
# x1 is repeated five times
# Manually adjust vector length
x1 <- c(1, 2, rep(0, 8))
x1 + x2
## [1] 2 4 3 4 5 6 7 8 9 10
students <- data.frame(
name = c("Ana", "Ben", "Cleo", "Dev",
"Eli", "Fay", "Gus", "Hana"),
major = c("Econ", "Soc", "Econ", "Soc",
"PoliSci", "PoliSci", "Econ", "Soc"),
hours = c(5, 2, 8, 6, 4, 7, 1, 4),
score = c(85, 70, 92, 88, 75, 90, 60, 80)
)
# BASE R
studied <- students[students$hours >= 4, ]
mean(studied$score, na.rm = TRUE)
## [1] 85
# Base R in one line
mean(
students$score[students$hours >= 4],
na.rm = TRUE
)
## [1] 85
# TIDYVERSE
students |>
filter(hours >= 4) |>
summarize(
avg_score = mean(score, na.rm = TRUE)
)
## avg_score
## 1 85
| Question | Answer |
|---|---|
| What is Base R? | Core functions and features built into R |
| Data type vs data structure? | Kind of value vs how values are organized |
| Vector vs list? | Vector has one type; list can have mixed types |
| Matrix vs data frame? | Matrix has one type; data frame can have different column types |
v[2]? |
Selects second vector element |
df[1, ]? |
Selects first row |
df[, 1]? |
Selects first column |
[ ] vs [[ ]] for lists? |
Sublist vs actual contents |
| What is vector recycling? | Repeating shorter vector during an operation |
select() vs pull()? |
Data frame vs vector |
TRUE or FALSE.| Type | What it does | Syntax |
|---|---|---|
if / else |
Tests one condition | if (condition) {} else {} |
if / else if / else |
Tests multiple conditions | if () {} else if () {} else {} |
Nested if |
Tests conditions within conditions | if () { if () {} } |
ifelse() |
Tests each element of a vector | ifelse(condition, TRUE, FALSE) |
if / else when there are two possible actions.else block runs.if statements evaluate a single logical
condition.Syntax:
if (condition) {
action1
} else {
action2
}
Example:
age <- 14
if (age > 16) {
print("You can get a driving license")
} else {
print("You cannot drive")
}
## [1] "You cannot drive"
Another example using mean():
movie_rating <- c(4.5, 4.2, 5.0, 3.8, 2.9, 1.7)
movie_rating_avg <- mean(movie_rating)
if (movie_rating_avg >= 4) {
print("This movie is great!")
} else {
print("Not a favorite.")
}
## [1] "Not a favorite."
movie_rating_avg.{} even when they are technically optional, to
improve readability.Syntax:
if (condition1) {
action1
} else if (condition2) {
action2
} else {
action3
}
Example 1:
x <- 0
if (x > 0) {
print("x is positive")
} else if (x < 0) {
print("x is negative")
} else {
print("x is zero")
}
## [1] "x is zero"
Example 2: Weather
temperature <- 25
if (temperature >= 30) {
weather <- "Hot"
} else if (temperature >= 20) {
weather <- "Cool"
} else if (temperature >= 10) {
weather <- "Breezy"
} else {
weather <- "Freezing"
}
print(weather)
## [1] "Cool"
temperature = 25 gives "Cool".temperature >= 20 becomes
TRUE.temperature >= 10 appeared first, the result
could be incorrect.| Operator | Meaning | Example |
|---|---|---|
& |
AND: both conditions must be TRUE | x >= 0 & x < 10 |
| |
OR: at least one condition must be TRUE | x < 0 | x > 30 |
== |
Equal to | x == 10 |
!= |
Not equal to | x != 10 |
%% |
Modulo: remainder after division | x %% 2 |
temperature <- 25
# AND: both conditions must be TRUE
if (temperature >= 0 & temperature < 10) {
weather <- "Cold"
} else {
weather <- "Warm"
}
print(weather)
## [1] "Warm"
# OR: either condition can be TRUE
if (temperature >= 0 | temperature < 10) {
weather <- "Cold"
} else {
weather <- "Warm"
}
print(weather)
## [1] "Cold"
& means both conditions have to be satisfied.| means only one condition needs to be satisfied.if statement placed inside
another if statement.%% 2 == 0 checks whether a number is even.%% 2 == 1 checks whether a positive integer is
odd.x <- 15
if (x > 0) {
if (x %% 2 == 0) {
print("x is a positive even number")
} else {
print("x is a positive odd number")
}
} else if (x < 0) {
if (x %% 2 == 0) {
print("x is a negative even number")
} else {
print("x is a negative odd number")
}
} else {
print("x is zero")
}
## [1] "x is a positive odd number"
ifelse() applies a condition to each element of
a vector.if / else, it can process multiple
values at once.ifelse(condition, value_if_TRUE, value_if_FALSE).# Single value
ifelse(sqrt(16) > 3,
sqrt(16),
0)
## [1] 4
# Vector
numbers <- c(10, 6, 7)
ifelse(numbers %% 2 == 1,
"odd",
"even")
## [1] "even" "even" "odd"
# Output: "even" "even" "odd"
Another example:
x <- c(5, 10, 15)
ifelse(x > 10, "High", "Low")
## [1] "Low" "Low" "High"
# Output: "Low" "Low" "High"
mutate(), R can directly access column
names.mutate(), use $ or
[[ ]] to extract columns.library(tidyverse)
qualify <- tibble(
athlet = c("Noah", "Julio", "Nick", "Maria"),
scores = c(32, 37, 28, 30)
)
# Tidyverse
qualify |>
mutate(
status = ifelse(
scores > 30,
"Admitted",
"Rejected"
)
)
## # A tibble: 4 × 3
## athlet scores status
## <chr> <dbl> <chr>
## 1 Noah 32 Admitted
## 2 Julio 37 Admitted
## 3 Nick 28 Rejected
## 4 Maria 30 Rejected
# Base R: return a vector
ifelse(qualify$scores > 30,
"Admitted",
"Rejected")
## [1] "Admitted" "Admitted" "Rejected" "Rejected"
# Base R: add new column
qualify$status <- ifelse(
qualify$scores > 30,
"Admitted",
"Rejected"
)
qualify |>
mutate(
status = ifelse(
scores > 35,
"Admitted",
ifelse(
scores >= 30,
"Waitlisted",
"Rejected"
)
)
)
## # A tibble: 4 × 3
## athlet scores status
## <chr> <dbl> <chr>
## 1 Noah 32 Waitlisted
## 2 Julio 37 Admitted
## 3 Nick 28 Rejected
## 4 Maria 30 Waitlisted
ifelse() works but may be harder to read.mutate()
steps.qualify |>
mutate(status = "Rejected") |>
mutate(
status = ifelse(
scores >= 30,
"Waitlisted",
status
)
) |>
mutate(
status = ifelse(
scores > 35,
"Admitted",
status
)
)
## # A tibble: 4 × 3
## athlet scores status
## <chr> <dbl> <chr>
## 1 Noah 32 Waitlisted
## 2 Julio 37 Admitted
## 3 Nick 28 Rejected
## 4 Maria 30 Waitlisted
ifelse() works well for two possible results.case_when() is generally easier to read for multiple
categories.case_when() for recoding
variables.data <- tibble(
decisionDirection = c(1, 2, 3, NA)
)
# Using ifelse()
data |>
mutate(
decision_direction = ifelse(
decisionDirection == 3,
NA,
decisionDirection - 1
)
)
## # A tibble: 4 × 2
## decisionDirection decision_direction
## <dbl> <dbl>
## 1 1 0
## 2 2 1
## 3 3 NA
## 4 NA NA
# Using case_when()
data |>
mutate(
decision_direction = case_when(
decisionDirection == 1 ~ 0,
decisionDirection == 2 ~ 1,
TRUE ~ NA_real_
)
)
## # A tibble: 4 × 2
## decisionDirection decision_direction
## <dbl> <dbl>
## 1 1 0
## 2 2 1
## 3 3 NA
## 4 NA NA
| Question | Answer |
|---|---|
| What are control structures? | Code that changes execution based on conditions or repetition |
if vs ifelse()? |
if tests one condition;
ifelse() works element-wise on vectors |
| Why does condition order matter? | R runs the first TRUE branch and skips the rest |
What does else do? |
Runs when previous conditions are FALSE |
What is a nested if? |
One conditional inside another |
What does %% do? |
Returns remainder after division |
& vs |? |
AND vs OR |
| How to add conditional values to a column? | Use mutate() with
ifelse() |
ifelse() vs case_when()? |
case_when() is easier to read for multiple
conditions |
i is commonly used as the loop variable, but any valid
name works.Syntax:
for (item in sequence) {
# Action repeated for each item
}
Example:
for (item in c(1, 2, 3)) {
print(item)
}
## [1] 1
## [1] 2
## [1] 3
# Prints 1, 2, 3
for (i in c(1, 2, 3)) {
print(i)
for (j in c("cat", "dog", "squirrel", "rabbit")) {
print(j)
}
}
## [1] 1
## [1] "cat"
## [1] "dog"
## [1] "squirrel"
## [1] "rabbit"
## [1] 2
## [1] "cat"
## [1] "dog"
## [1] "squirrel"
## [1] "rabbit"
## [1] 3
## [1] "cat"
## [1] "dog"
## [1] "squirrel"
## [1] "rabbit"
# Outer loop runs 3 times
# Inner loop runs 4 times for each outer iteration
# Total inner-loop iterations = 12
{}.print() to track the current value of
variables.for (i in c(1, 2, 3)) {
print(i)
print("Hello")
my_sum <- 100 + i
print(my_sum)
print(paste("End of Loop", i))
}
## [1] 1
## [1] "Hello"
## [1] 101
## [1] "End of Loop 1"
## [1] 2
## [1] "Hello"
## [1] 102
## [1] "End of Loop 2"
## [1] 3
## [1] "Hello"
## [1] 103
## [1] "End of Loop 3"
my_sum <- 0
for (i in c(1, 2, 3)) {
my_sum <- my_sum + i
print(my_sum)
}
## [1] 1
## [1] 3
## [1] 6
# Output: 1, 3, 6
# Final my_sum = 6
my_sum <- my_sum + i means adding the current value
of i to the existing total.vector() to create an output vector before the
loop.output[i].mode according to the type of output.my_sum <- 0
output <- vector(
mode = "integer",
length = 3
)
for (i in c(1, 2, 3)) {
my_sum <- my_sum + i
output[i] <- my_sum
}
output
## [1] 1 3 6
# Output: 1, 3, 6
i represents the actual
element.i represents the position of
the element.| Type | Syntax | Meaning |
|---|---|---|
| Values | for (i in x) |
i takes the values in x |
| Indexes | for (i in seq_along(x)) |
i takes the positions of x |
| Extract value | x[i] |
Value at position i |
x <- c(1, 4, 6)
# Loop over VALUES
for (i in x) {
print(i)
}
## [1] 1
## [1] 4
## [1] 6
# Prints 1, 4, 6
# Loop over INDEXES
for (i in seq_along(x)) {
print(i)
print(x[i])
}
## [1] 1
## [1] 1
## [1] 2
## [1] 4
## [1] 3
## [1] 6
# i = 1, 2, 3
# x[i] = 1, 4, 6
seq_along(x) generates the positions of elements in
x.1:length(x).x <- c(1, 4, 6)
# Indexes
seq_along(x)
## [1] 1 2 3
# 1, 2, 3
# Recommended
for (i in seq_along(x)) {
print(x[i])
}
## [1] 1
## [1] 4
## [1] 6
x <- c(1, 4, 6)
my_sum <- 0
output <- vector(
mode = "integer",
length = length(x)
)
for (i in seq_along(x)) {
my_sum <- my_sum + x[i]
output[i] <- my_sum
}
output
## [1] 1 5 11
# Output: 1, 5, 11
i is the position, NOT the value.x[i] extracts the value at that position.output[i] stores the running total in the correct
position.ifelse(), which performs vectorized
tests.numbers <- c(10, 6, 7)
# Using vectorized ifelse()
ifelse(
numbers %% 2 == 1,
"odd",
"even"
)
## [1] "even" "even" "odd"
# Using for loop + if/else
for (i in seq_along(numbers)) {
if (numbers[i] %% 2 == 1) {
print("odd")
} else {
print("even")
}
}
## [1] "even"
## [1] "even"
## [1] "odd"
[[ ]].seq_along(df) produces column indexes.df[[i]] extracts the actual column as a vector.library(tidyverse)
library(palmerpenguins)
##
## Attaching package: 'palmerpenguins'
## The following objects are masked from 'package:datasets':
##
## penguins, penguins_raw
# Keep only numeric columns
penguins_numeric <- penguins |>
select(where(is.numeric))
# Create output vector
output <- vector(
mode = "double",
length = ncol(penguins_numeric)
)
# Calculate mean of each numeric column
for (i in seq_along(penguins_numeric)) {
output[i] <- mean(
penguins_numeric[[i]],
na.rm = TRUE
)
}
output
## [1] 43.92193 17.15117 200.91520 4201.75439 2008.02907
penguins; in
practice, numeric columns are selected here first so mean()
is appropriate for every selected column.| Syntax | What it returns | Example |
|---|---|---|
df[i] |
Data frame containing one column | penguins[3] |
df[[i]] |
Vector containing column values | penguins[[3]] |
output[i] |
Position i in a vector | output[2] |
# One-column data frame
penguins[3]
## # A tibble: 344 × 1
## bill_length_mm
## <dbl>
## 1 39.1
## 2 39.5
## 3 40.3
## 4 NA
## 5 36.7
## 6 39.3
## 7 38.9
## 8 39.2
## 9 34.1
## 10 42
## # ℹ 334 more rows
# Extract column vector
penguins[[3]]
## [1] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42.0 37.8 37.8 41.1 38.6 34.6
## [16] 36.6 38.7 42.5 34.4 46.0 37.8 37.7 35.9 38.2 38.8 35.3 40.6 40.5 37.9 40.5
## [31] 39.5 37.2 39.5 40.9 36.4 39.2 38.8 42.2 37.6 39.8 36.5 40.8 36.0 44.1 37.0
## [46] 39.6 41.1 37.5 36.0 42.3 39.6 40.1 35.0 42.0 34.5 41.4 39.0 40.6 36.5 37.6
## [61] 35.7 41.3 37.6 41.1 36.4 41.6 35.5 41.1 35.9 41.8 33.5 39.7 39.6 45.8 35.5
## [76] 42.8 40.9 37.2 36.2 42.1 34.6 42.9 36.7 35.1 37.3 41.3 36.3 36.9 38.3 38.9
## [91] 35.7 41.1 34.0 39.6 36.2 40.8 38.1 40.3 33.1 43.2 35.0 41.0 37.7 37.8 37.9
## [106] 39.7 38.6 38.2 38.1 43.2 38.1 45.6 39.7 42.2 39.6 42.7 38.6 37.3 35.7 41.1
## [121] 36.2 37.7 40.2 41.4 35.2 40.6 38.8 41.5 39.0 44.1 38.5 43.1 36.8 37.5 38.1
## [136] 41.1 35.6 40.2 37.0 39.7 40.2 40.6 32.1 40.7 37.3 39.0 39.2 36.6 36.0 37.8
## [151] 36.0 41.5 46.1 50.0 48.7 50.0 47.6 46.5 45.4 46.7 43.3 46.8 40.9 49.0 45.5
## [166] 48.4 45.8 49.3 42.0 49.2 46.2 48.7 50.2 45.1 46.5 46.3 42.9 46.1 44.5 47.8
## [181] 48.2 50.0 47.3 42.8 45.1 59.6 49.1 48.4 42.6 44.4 44.0 48.7 42.7 49.6 45.3
## [196] 49.6 50.5 43.6 45.5 50.5 44.9 45.2 46.6 48.5 45.1 50.1 46.5 45.0 43.8 45.5
## [211] 43.2 50.4 45.3 46.2 45.7 54.3 45.8 49.8 46.2 49.5 43.5 50.7 47.7 46.4 48.2
## [226] 46.5 46.4 48.6 47.5 51.1 45.2 45.2 49.1 52.5 47.4 50.0 44.9 50.8 43.4 51.3
## [241] 47.5 52.1 47.5 52.2 45.5 49.5 44.5 50.8 49.4 46.9 48.4 51.1 48.5 55.9 47.2
## [256] 49.1 47.3 46.8 41.7 53.4 43.3 48.1 50.5 49.8 43.5 51.5 46.2 55.1 44.5 48.8
## [271] 47.2 NA 46.8 50.4 45.2 49.9 46.5 50.0 51.3 45.4 52.7 45.2 46.1 51.3 46.0
## [286] 51.3 46.6 51.7 47.0 52.0 45.9 50.5 50.3 58.0 46.4 49.2 42.4 48.5 43.2 50.6
## [301] 46.7 52.0 50.5 49.5 46.4 52.8 40.9 54.2 42.5 51.0 49.7 47.5 47.6 52.0 46.9
## [316] 53.5 49.0 46.2 50.9 45.5 50.9 50.8 50.1 49.0 51.5 49.8 48.1 51.4 45.7 50.7
## [331] 42.5 52.2 45.2 49.3 50.2 45.6 51.9 46.8 45.7 55.8 43.5 49.6 50.8 50.2
# Check structure
is.data.frame(penguins[3])
## [1] TRUE
is.vector(penguins[[3]])
## [1] TRUE
| Question | Answer |
|---|---|
| What does a for loop do? | Repeats code for each element |
| What is a nested loop? | A loop inside another loop |
| How to calculate a running total? | Initialize before the loop, then update each iteration |
| What is pre-allocation? | Creating output storage before looping |
| Values vs indexes? | Actual elements vs their positions |
Why use seq_along()? |
Safely generates indexes |
i vs x[i]? |
Position vs element at that position (when looping over indexes) |
df[i] vs df[[i]]? |
Data frame vs vector |
| Can for loops contain if statements? | Yes |
| When to use a loop? | When an action must be repeated across elements |
map_*() from purrracross() from dplyrapply() family from Base R| Function | Package | What it does | Best used for |
|---|---|---|---|
map_*() |
purrr | Applies function to each element | Lists, vectors, data frame columns |
across() |
dplyr | Applies same function to several columns | Inside mutate() or summarize() |
apply() |
Base R | Applies function across rows or columns | Matrices |
lapply() |
Base R | Applies function to each element | Returns a list |
sapply() |
Base R | Applies function to each element | Simplifies output when possible |
map_*() family comes from the purrr package.| Function | Output |
|---|---|
map() |
List |
map_lgl() |
Logical vector |
map_int() |
Integer vector |
map_dbl() |
Double vector |
map_chr() |
Character vector |
library(tidyverse)
library(palmerpenguins)
# Calculate mean for every numeric column
penguins |>
select(where(is.numeric)) |>
map_dbl(mean, na.rm = TRUE)
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## 43.92193 17.15117 200.91520 4201.75439
## year
## 2008.02907
# Calculate median instead
penguins |>
select(where(is.numeric)) |>
map_dbl(median, na.rm = TRUE)
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## 44.45 17.30 197.00 4050.00
## year
## 2008.00
# Using map() returns a list
penguins |>
select(where(is.numeric)) |>
map(mean, na.rm = TRUE)
## $bill_length_mm
## [1] 43.92193
##
## $bill_depth_mm
## [1] 17.15117
##
## $flipper_length_mm
## [1] 200.9152
##
## $body_mass_g
## [1] 4201.754
##
## $year
## [1] 2008.029
map_dbl() returns a double vector.map() returns a list.select(where(is.numeric)) ensures that only numeric
columns are used.across() comes from dplyr.mutate() or
summarize()..cols: selects columns..fns: specifies the function..names: controls output column names.# Calculate mean of all numeric columns
penguins |>
summarize(
across(
.cols = where(is.numeric),
.fns = ~ mean(.x, na.rm = TRUE)
)
)
## # A tibble: 1 × 5
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g year
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 43.9 17.2 201. 4202. 2008.
# Shorter version
penguins |>
summarize(
across(
where(is.numeric),
~ mean(.x, na.rm = TRUE)
)
)
## # A tibble: 1 × 5
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g year
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 43.9 17.2 201. 4202. 2008.
# Customize output column names
penguins |>
summarize(
across(
.cols = where(is.numeric),
.fns = ~ mean(.x, na.rm = TRUE),
.names = "avg_{.col}"
)
)
## # A tibble: 1 × 5
## avg_bill_length_mm avg_bill_depth_mm avg_flipper_length_mm avg_body_mass_g
## <dbl> <dbl> <dbl> <dbl>
## 1 43.9 17.2 201. 4202.
## # ℹ 1 more variable: avg_year <dbl>
.x represents the current column."avg_{.col}" adds avg_ before the original
column name.across() works within a dplyr function;
map_*() can also be used independently.apply() is a Base R function.apply(X, MARGIN, FUN).MARGIN = 1: apply function to rows.MARGIN = 2: apply function to columns.apply() on mixed-type data
frames, because it converts them to matrices.m <- matrix(
1:9,
nrow = 3,
byrow = TRUE
)
# Mean of each row
apply(m, 1, mean)
## [1] 2 5 8
# Mean of each column
apply(m, 2, mean)
## [1] 4 5 6
Using apply() with the penguins data:
penguins |>
select(where(is.numeric)) |>
apply(2, mean, na.rm = TRUE)
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## 43.92193 17.15117 200.91520 4201.75439
## year
## 2008.02907
lapply() always returns a list.sapply() attempts to simplify the result.x <- list(
a = c(1, 2, 3),
b = c(4, 5, 6)
)
# Returns list
lapply(x, mean)
## $a
## [1] 2
##
## $b
## [1] 5
# Returns simplified vector
sapply(x, mean)
## a b
## 2 5
library(tidyverse)
library(palmerpenguins)
penguins_numeric <- penguins |>
select(where(is.numeric))
# For loop
output <- vector(
mode = "double",
length = ncol(penguins_numeric)
)
for (i in seq_along(penguins_numeric)) {
output[i] <- mean(
penguins_numeric[[i]],
na.rm = TRUE
)
}
output
## [1] 43.92193 17.15117 200.91520 4201.75439 2008.02907
# map_dbl()
penguins_numeric |>
map_dbl(mean, na.rm = TRUE)
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## 43.92193 17.15117 200.91520 4201.75439
## year
## 2008.02907
# across()
penguins_numeric |>
summarize(
across(
everything(),
~ mean(.x, na.rm = TRUE)
)
)
## # A tibble: 1 × 5
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g year
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 43.9 17.2 201. 4202. 2008.
# apply()
apply(
penguins_numeric,
2,
mean,
na.rm = TRUE
)
## bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## 43.92193 17.15117 200.91520 4201.75439
## year
## 2008.02907
seq_along(x) rather than
1:length(x).Syntax:
while (condition) {
# Statements repeated while condition is TRUE
}
Example:
counter <- 1
while (counter <= 5) {
print(counter)
counter <- counter + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
| For Loop | While Loop |
|---|---|
| Iterates through a known sequence | Repeats while a condition is TRUE |
| Useful when items are known | Useful when number of repetitions is unknown |
for (i in x) {} |
while (condition) {} |
Syntax:
function_name <- function(argument) {
# Code using argument
return(result)
}
Example: Calculate the sum of a vector
my_sum <- function(vector) {
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(total)
}
x <- c(2, 1, 5, 2)
my_sum(x)
## [1] 10
# Output: 10
function(vector) defines the input.total <- 0 initializes the total.return(total) gives the result back.my_sum <- function(vector) {
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(total)
}
my_sum(c(1, 2, 3))
## [1] 6
# total exists only inside the function
# total outside the function may produce an error
return() exits a function normally and provides a
value.return() will not run.# Explicit return
add <- function(x) {
result <- x + 3
return(result)
}
add(2)
## [1] 5
# Implicit return
add <- function(x) {
x + 3
}
add(2)
## [1] 5
Multiple return statements:
describe_number <- function(x) {
if (x == 0) {
return("x is zero")
}
if (x > 0) {
return("x is positive")
} else {
return("x is negative")
}
}
describe_number(0)
## [1] "x is zero"
describe_number(3)
## [1] "x is positive"
describe_number(-3)
## [1] "x is negative"
list() when returning multiple objects.$ or [[ ]].my_sum <- function(vector) {
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(
list(
total = total,
n = length(vector)
)
)
}
x <- c(2, 1, 5, 2)
y <- my_sum(x)
y$total
## [1] 10
y$n
## [1] 4
y[[1]]
## [1] 10
stop() halts a function and produces an error.return() indicates normal completion.stop() indicates failure.my_sum <- function(vector) {
if (missing(vector)) {
stop("You must provide a vector")
}
if (!is.numeric(vector)) {
stop("Input must be a numeric vector")
}
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(total)
}
# Valid
my_sum(c(2, 1, 5, 2))
## [1] 10
# Invalid inputs (run separately to see errors):
# my_sum(c("one", 2, 3))
# my_sum()
Another example: Celsius to Fahrenheit
celsius_to_fahr <- function(celsius) {
if (!is.numeric(celsius)) {
stop("Input must be numeric")
} else {
fahr <- (celsius * 9/5) + 32
return(fahr)
}
}
celsius_to_fahr(0)
## [1] 32
celsius_to_fahr(-20)
## [1] -4
| Question | Answer |
|---|---|
| Why use alternatives to for loops? | More concise repeated operations |
map() vs map_dbl()? |
List vs double vector |
What does across() do? |
Applies a function to multiple columns |
.cols vs .fns? |
Columns selected vs function applied |
apply(X, 1, FUN)? |
Apply function to rows |
apply(X, 2, FUN)? |
Apply function to columns |
lapply() vs sapply()? |
List vs simplified output |
| For vs while loop? | Known sequence vs condition-controlled repetition |
| Why initialize a counter in while loops? | To control when the loop stops |
| What is a custom function? | A reusable block of code with arguments |
| What is function scope? | Variables defined inside a function are local |
return() vs stop()? |
Normal output vs error |
| Why return a list? | To return multiple objects, possibly of different types |
| Syntax | Description |
|---|---|
function(x) x + 3 |
Standard anonymous function |
\(x) x + 3 |
Base R shortcut (R 4.1+) |
~ .x + 3 |
Formula shorthand supported by purrr and some tidyverse functions |
# Named function
add <- function(x) {
return(x + 3)
}
add(2)
## [1] 5
# Anonymous function
(function(x) x + 3)(2)
## [1] 5
# Same using {}
(function(x) {x + 3})(2)
## [1] 5
# Base R shortcut
(\(x) x + 3)(2)
## [1] 5
Using vectors:
# Named function
add <- function(x) {
return(x + 3)
}
add(c(1, 2, 3))
## [1] 4 5 6
# Anonymous function
(function(x) x + 3)(c(1, 2, 3))
## [1] 4 5 6
# Shortcut
(\(x) x + 3)(c(1, 2, 3))
## [1] 4 5 6
lapply() and sapply() apply functions to
elements of a vector or list.lapply() returns a list.sapply() tries to simplify the output.# Using sapply()
sapply(
c(1, 2, 3),
function(x) x + 3
)
## [1] 4 5 6
# Using shorthand
sapply(
c(1, 2, 3),
\(x) x + 3
)
## [1] 4 5 6
# Using lapply()
lapply(
c(1, 2, 3),
function(x) x + 3
)
## [[1]]
## [1] 4
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 6
lapply(
c(1, 2, 3),
\(x) x + 3
)
## [[1]]
## [1] 4
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 6
Example: Calculate mean of each element in a list
l <- list(1:5, 5:7)
# lapply() - returns list
lapply(
l,
function(x) sum(x) / length(x)
)
## [[1]]
## [1] 3
##
## [[2]]
## [1] 6
# sapply() - returns simplified vector
sapply(
l,
function(x) sum(x) / length(x)
)
## [1] 3 6
map_*() family supports multiple anonymous function
syntaxes.function(x) and \(x) are Base R
syntax.~ .x is purrr-style shorthand.map_dbl() returns a double vector.map() returns a list.library(purrr)
# Standard anonymous function
map_dbl(
c(1, 2, 3),
function(x) x + 3
)
## [1] 4 5 6
# Base R shorthand
map_dbl(
c(1, 2, 3),
\(x) x + 3
)
## [1] 4 5 6
# purrr shorthand
map_dbl(
c(1, 2, 3),
~ .x + 3
)
## [1] 4 5 6
# map() returns a list
map(
c(1, 2, 3),
~ .x + 3
)
## [[1]]
## [1] 4
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 6
sapply(), map_*(), and
across().library(tidyverse)
library(palmerpenguins)
# Base R: named vector
sapply(
penguins,
\(x) sum(is.na(x))
)
## species island bill_length_mm bill_depth_mm
## 0 0 2 2
## flipper_length_mm body_mass_g sex year
## 2 2 11 0
# purrr: integer vector
map_int(
penguins,
\(x) sum(is.na(x))
)
## species island bill_length_mm bill_depth_mm
## 0 0 2 2
## flipper_length_mm body_mass_g sex year
## 2 2 11 0
# dplyr: one-row data frame
penguins |>
summarize(
across(
everything(),
\(x) sum(is.na(x))
)
)
## # A tibble: 1 × 8
## species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## <int> <int> <int> <int> <int> <int>
## 1 0 0 2 2 2 2
## # ℹ 2 more variables: sex <int>, year <int>
Calculate means for several columns by group:
penguins |>
group_by(species) |>
summarize(
across(
bill_length_mm:body_mass_g,
\(x) mean(x, na.rm = TRUE)
)
)
## # A tibble: 3 × 5
## species bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
## <fct> <dbl> <dbl> <dbl> <dbl>
## 1 Adelie 38.8 18.3 190. 3701.
## 2 Chinstrap 48.8 18.4 196. 3733.
## 3 Gentoo 47.5 15.0 217. 5076.
#')##' Calculate the sum of a numeric vector
#'
#' @param vector A numeric vector
#' @return A single number: sum of elements
my_sum <- function(vector) {
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(total)
}
@param describes an argument.@return describes the output.my_sum <- function(vector) {
# Calculates the sum of a numeric vector.
#
# Args:
# vector: a numeric vector.
#
# Returns:
# A single number: sum of all elements.
#
# Example:
# my_sum(c(3, 1, 4))
total <- 0
for (i in seq_along(vector)) {
total <- total + vector[i]
}
return(total)
}
my_sum(c(3, 1, 4))
## [1] 8
{{ }}.{{ col }} tells dplyr to use the column passed as an
argument.Example data:
library(dplyr)
df <- tibble(
age = c(10, 12, 13, 14, 10),
height = c(110, 140, 155, 170, 130)
)
df
## # A tibble: 5 × 2
## age height
## <dbl> <dbl>
## 1 10 110
## 2 12 140
## 3 13 155
## 4 14 170
## 5 10 130
Without custom functions:
df |>
summarize(
mean_age = mean(age),
sd_age = sd(age)
)
## # A tibble: 1 × 2
## mean_age sd_age
## <dbl> <dbl>
## 1 11.8 1.79
Without {{ }}, this function does not work as
intended:
# Incorrect: col will not refer to the passed column
custom_summary <- function(data, col) {
data |>
summarize(
mean_value = mean(col),
sd_value = sd(col)
)
}
custom_summary(df, age)
Correct code:
custom_summary <- function(data, col) {
data |>
summarize(
mean_value = mean({{ col }}),
sd_value = sd({{ col }})
)
}
custom_summary(df, age)
## # A tibble: 1 × 2
## mean_value sd_value
## <dbl> <dbl>
## 1 11.8 1.79
# mean_value = 11.8
# sd_value approximately 1.79
data is the input data frame.col represents the column passed into the
function.{{ col }} allows dplyr to evaluate that supplied
column.{{ }} inside across() to select
multiple columns.custom_summary <- function(data, cols) {
data |>
summarize(
across(
{{ cols }},
list(mean = mean, sd = sd)
)
)
}
custom_summary(
df,
c(age, height)
)
## # A tibble: 1 × 4
## age_mean age_sd height_mean height_sd
## <dbl> <dbl> <dbl> <dbl>
## 1 11.8 1.79 141 23.0
# Returns:
# age_mean, age_sd, height_mean, height_sd
| Type | Common Functions |
|---|---|
| Data masking | mutate(), filter(),
summarize(), group_by(),
arrange(), aes() |
| Tidy selection | select(), rename(),
relocate(), across(),
pivot_longer() |
Example using filter():
# Create a reusable filtering function
filter_above <- function(data, col, cutoff) {
data |>
filter({{ col }} > cutoff)
}
filter_above(
df,
age,
11
)
## # A tibble: 3 × 2
## age height
## <dbl> <dbl>
## 1 12 140
## 2 13 155
## 3 14 170
| Question | Answer |
|---|---|
| What is an anonymous function? | A function without a name |
| When should we use anonymous functions? | Short operations needed only once |
function(x) vs \(x)? |
Standard vs shorthand syntax |
What does ~ .x mean? |
purrr-style anonymous function |
lapply() vs sapply()? |
Always list vs simplified output |
map() vs map_dbl()? |
List vs double vector |
| Why document a function? | Explain what it does, its inputs and outputs |
What does @param mean? |
Describes an argument |
What does @return mean? |
Describes the return value |
| What is embracing? | Using {{ }} to pass columns into tidyverse
functions |
Why use {{ col }}? |
To evaluate the supplied column rather than a literal column named col |
| Data masking vs tidy selection? | Computing with columns vs selecting columns |