Сила итерации

Основы функционального программирования с purrr

Auriel Fournier

Instructor

Итерация без 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)
}
Основы функционального программирования с purrr

Итерация без 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])
}
Основы функционального программирования с purrr

Итерация с purrr

map(object, function)

object - может быть вектором или списком

function - любая функция R, принимающая элементы объекта

d <- map(files, read_csv)
Основы функционального программирования с purrr

Разберём пример

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
Основы функционального программирования с 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
Основы функционального программирования с purrr

Давайте потренируемся!

Основы функционального программирования с purrr

Preparing Video For Download...