map2() and pmap()

Foundations of Functional Programming with purrr

Auriel Fournier

Instructor

list_of_means
[[1]]
[1] 5
[[2]]
[1] 2
[[3]]
[1] 300
[[4]]
[1] 15
simdata <- map2(list_of_means, 
                list_of_sd, 
     ~data.frame(a = rnorm(mean=.x, 
                n=200, sd=.y),
                b = rnorm(mean=200, 
                n=200, sd=15)))
head(simdata[[1]])
list_of_sd
[[1]]
[1] 0.5
[[2]]
[1] 0.01
[[3]]
[1] 20
[[4]]
[1] 1
         a        b
1 4.986100 195.1436
2 5.216531 222.7807
3 4.249028 201.0155
4 5.125663 189.3022
5 4.430192 231.3301
6 5.557537 185.3563
Foundations of Functional Programming with purrr

What if we didn't use purrr?

for(i in list_of_means){
  for(j in list_of_sd){
    for(k in list_of_samplesize){
    num <- 1
      simdata[[1]] <- rnorm(mean=i, sd=j, n = k)
    num <- num + 1
    }
  }
}
Foundations of Functional Programming with purrr
list_of_means
list_of_sd
list_of_samplesize
[[1]]
[1] 5
[[2]]
[1] 2
...
[[1]]
[1] 0.5
[[2]]
[1] 0.01
...
[[1]]
[1] 200
[[2]]
[1] 50
...
input_list <- list(
    means = list_of_means,
    sd = list_of_sd,
    samplesize = list_of_samplesize)
str(input_list)
List of 3
 $ means     :List of 4
  ..$ : num 5
  ..$ : num 2
  ..$ : num 300
  ..$ : num 15
 $ sd        :List of 4
  ..$ : num 0.5
  ..$ : num 0.01
  ..$ : num 20
  ..$ : num 1
 $ samplesize:List of 4
  ..$ : num 200
  ..$ : num 50
...
Foundations of Functional Programming with purrr

pmap()

simdata <- pmap(inputs_list, 
     function(means, sd, samplesize)
     data.frame(a = rnorm(mean=means,
                            n=samplesize, 
                            sd=sd)))
head(simdata[[1]])
         a
1 5.862376
2 5.308204
3 4.771946
4 5.173814
5 4.674113
6 4.681016
Foundations of Functional Programming with purrr

Let's purrr-actice!

Foundations of Functional Programming with purrr

Preparing Video For Download...