purrr::pmap with other default inputs
Asked Answered
Q

1

5

I am wondering how to use pmap() function if I have more than 3 inputs as parameters to map into a function with other default inputs.

Here is a reproducible example:

a=c(5, 100, 900)
b=c(1, 2, 3)
ablist=list(mean=a,sd=b)
pmap(ablist, ~rnorm( mean=a , sd=b , n = 9))

outputs:

 [[1]]
 [1]   5.734723  99.883171 895.962561   5.346905  98.723191 903.373177   4.172267  96.424440 897.437970

 [[2]]
 [1]   4.427977  98.348139 899.287248   4.404674  99.178516 900.983974   3.836353 101.520355 899.992332

 [[3]]
 [1]   4.961772  95.927525 899.096313   4.444354 101.694591 904.172462   6.231246  97.773325 897.611838

But as you can see, the output is not mapping the mean and sd in the order of vectors.

I want to have [[1]] with rnorm(mean=5,sd=1,n=9) and so on. Out of curiosity, I am wondering what pmap() is doing for this demo.

By the way, I know in this example, I can easily use map2() without any hassle but in my real code, I have 10 inputs so I need to use pmap().

Thanks in advance for any replies!

Quintie answered 20/12, 2018 at 18:38 Comment(0)
N
7

When you are using pmap, you can refer to your arguments with ..1, ..2, etc. This should give you what you want:

pmap(ablist, ~rnorm(mean = ..1, sd = ..2, n = 9))

Alternatively you can supply a named list with all of the arguments included. This works as well:

abclist = list(
  mean = c(5, 100, 900),
  sd = c(1, 2, 3), 
  n = rep(9, 3)
)

pmap(abclist, rnorm)

Your code is just running rnorm(mean = c(5, 100, 900), sd = c(1, 2, 3), n = 9) 3 times and storing it in a list.

Nordrheinwestfalen answered 20/12, 2018 at 18:45 Comment(2)
Wow! AWESOME!!! It works! I really appreciate your help! pmap() is very hard to understand though. Any suggests to learn it quickly?Quintie
You can also use pmap(ablist, rnorm, n = 9), as pmap uses ... to collect other parameters to pass into .fCarvalho

© 2022 - 2024 — McMap. All rights reserved.