Foundations of Functional Programming with purrr
Auriel Fournier
Instructor
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)
}
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])
}
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)
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
# 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