The power of iteration

Foundations of Functional Programming with purrr

Auriel Fournier

Instructor

Iteration without purrr

library(readr)
USbirds <- read_csv("us_data.csv")
CANbirds <- read_csv("can_data.csv")
MEXbirds <- read_csv("mex_data.csv")

birdfiles <- list.files(pattern=".csv") birdfiles
"can_data.csv"
"mex_data.csv"
"us_data.csv"
list_of_birdfiles <- list()
for(i in birdfiles){
list_of_birdfiles[[i]] <- read.csv(i)
}
Foundations of Functional Programming with purrr

Iteration without purrr

files <- list.files()
d <- list()

# Loop through the values 1 through 10, to add them to d
for(i in 1:10){
    d[[i]] <- read_csv(files[i])
}
Foundations of Functional Programming with purrr

Iteration with purrr

map(object, function)

object - can be a vector or a list

function - any function in R that takes the input offered by the object

d <- map(files, read_csv)
Foundations of Functional Programming with purrr

Let's work through an example

bird_counts
[[1]]
[1] 3 1

[[2]]
[1] 3 8 1 2

[[3]]
[1] 8 3 9 9 5 5

[[4]]
[1] 8 9 7 9 5 4 1 5
Foundations of Functional Programming with purrr
# Create bird_sum list, loop over and sum elements of bird_counts
bird_sum <- list()
for(i in seq_along(bird_counts)){
    bird_sum[[i]] <- sum(bird_counts[[i]])}

# Sum each element of bird_counts, and put it in bird_sum bird_sum <- map(bird_counts, sum) bird_sum
[[1]]
[1] 4

[[2]]
[1] 14

[[3]]
[1] 39

[[4]]
[1] 48
Foundations of Functional Programming with purrr

Let's purrr-actice!

Foundations of Functional Programming with purrr

Preparing Video For Download...