More map()

Foundations of Functional Programming with purrr

Auriel Fournier

Instructor

Simulate data

list_of_means
[[1]]
[1] 5

[[2]]
[1] 2

[[3]]
[1] 300

[[4]]
[1] 15
list_of_df <- map(list_of_means,  
    ~data.frame(a=rnorm(mean = .x,
                      n = 200,
                      sd = (5/2))))
head(list_of_df[[1]])
         a
1 4.518015
2 3.915059
3 5.306956
4 7.039757
5 8.609741
6 1.478696
Foundations of Functional Programming with purrr

Run linear models

str(education_data[[1]])
List of 2
 $ district_a:List of 2
  ..$ education_level: chr [1:200] "B.S." "K-12"  ...
  ..$ income         : num [1:200] 487256 493378  ...
models <- education_data %>%
    map(~ lm(income ~ education_level, data=.x)) %>%
    map(summary)
Foundations of Functional Programming with purrr

map_*() flavors

map(livingthings, 
    ~.x[["species"]])

[[1]] [1] "Purple Flowers" [[2]] [1] "Green Grass" [[3]] [1] "Brown Dog"
map_chr(livingthings, 
        ~.x[["species"]])

[1] "Purple Flowers" "Green Grass" "Brown Dog"
map_lgl(livingthings, 
~.x[["species"]]=="Purple Flowers")

[1] TRUE FALSE FALSE
Foundations of Functional Programming with purrr

map_*() flavors with numbers

map_dbl(bird_measurements, 
          ~.x[["wing length"]])
 sora robin 
   75    12
map_int(bird_measurements, 
          ~.x[["wing length"]])
 sora robin 
   75    12
map_dbl(bird_measurements, 
         ~.x[["weight"]])
 sora robin 
 96.4  76.5
map_int(bird_measurements, 
         ~.x[["weight"]])
Error: Can't coerce element 1 
from a double to a integer
Foundations of Functional Programming with purrr

map_df()

bird_measurements %>% 
   map_df(~ data_frame(weight=.x[["weight"]],
                       wing_length = .x[["wing length"]]))
# A tibble: 2 x 2
  weight wing_length
   <dbl>       <dbl>
1   96.4          75
2   76.5          12
Foundations of Functional Programming with purrr

Let's purrr-actice!

Foundations of Functional Programming with purrr

Preparing Video For Download...