purrr::pmap with other default inputs

2019-04-11 05:29发布

问题:

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!

回答1:

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.



标签: r purrr pmap