7.8 Mapping over different arguments
map2
and pmap
varying just a single value
mu <- list(5, 10, -3)
mu %>%
map(rnorm, n = 5) %>%
str()
## List of 3
## $ : num [1:5] 5.21 4.64 5.76 4.27 3.63
## $ : num [1:5] 10.43 9.19 11.44 9.57 10.66
## $ : num [1:5] -2.68 -3.78 -1.42 -2.36 -2.91
varying both mu and sigmna
sigma <- list(1, 5, 10)
map2(mu, sigma, rnorm, n = 5) %>% str()
## List of 3
## $ : num [1:5] 5.28 5.68 5.09 2.01 5.28
## $ : num [1:5] 8.16 10.93 12.91 17 6.36
## $ : num [1:5] 10.025 0.358 7.385 6.207 4.209
variying across mu, sigma, and n
pmap(args, rnorm) %>% str()
## List of 3
## $ : num 3.96
## $ : num [1:3] 9.55 13.12 5.23
## $ : num [1:5] -8.43 2.81 4.68 1.64 -11.86
If your data is all the same length it can be stored in a dataframe. Or if you have a dataframe of values you are planning to “apply” over.
library(tibble)
params <- tribble(
~mean, ~sd, ~n,
5, 1, 1,
10, 5, 3,
-3, 10, 5
)
params %>%
pmap(rnorm)
## [[1]]
## [1] 3.900219
##
## [[2]]
## [1] 17.56354 11.28961 10.44220
##
## [[3]]
## [1] -4.208965 -14.943289 3.119969 -5.171398 -4.827567
Having a dataframe and using list columns, you can change
the function an it’s arguments with invoke_map
f <- c("runif", "rnorm", "rpois")
param <- list(
list(min = -1, max = 1),
list(sd = 5),
list(lambda = 10)
)
invoke_map(f, param, n = 5) %>% str()
## List of 3
## $ : num [1:5] 0.649 0.185 0.589 0.538 0.836
## $ : num [1:5] 5.46 -3.23 3.33 4.09 -2.8
## $ : int [1:5] 12 17 13 13 6
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
sim <- tribble(
~f, ~params,
"runif", list(min = -1, max = 1),
"rnorm", list(sd = 5),
"rpois", list(lambda = 10)
)
sim_invoked <- sim %>%
mutate(sim = invoke_map(f, params, n = 10))
sim_invoked
## # A tibble: 3 x 3
## f params sim
## <chr> <list> <list>
## 1 runif <named list [2]> <dbl [10]>
## 2 rnorm <named list [1]> <dbl [10]>
## 3 rpois <named list [1]> <int [10]>
sim_invoked$sim
## [[1]]
## [1] -0.03082414 -0.49508312 -0.48062004 0.08403188 0.29975168 -0.32716174
## [7] -0.87810051 -0.09737830 0.67751007 0.14927467
##
## [[2]]
## [1] -1.881454 6.205581 -4.738676 8.839889 4.586639 -4.473877
## [7] -3.440830 -4.992420 -10.536207 4.287095
##
## [[3]]
## [1] 13 9 10 7 6 14 7 15 10 6