问题描述
我想知道如果我有超过 3 个输入作为参数映射到具有其他默认输入的函数,如何使用 pmap()
函数.
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))
输出:
[[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
但是正如您所看到的,输出并没有按照向量的顺序映射 mean
和 sd
.
But as you can see, the output is not mapping the mean
and sd
in the order of vectors.
我想要 [[1]]
和 rnorm(mean=5,sd=1,n=9)
等等.出于好奇,我想知道 pmap()
为这个演示做了什么.
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.
顺便说一下,我知道在这个例子中,我可以轻松地使用 map2()
而没有任何麻烦,但在我的实际代码中,我有 10 个输入,所以我需要使用 pmap()
.
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()
.
提前感谢您的回复!
推荐答案
当您使用 pmap
时,您可以使用 ..1
、 引用您的参数>..2
等.这应该给你你想要的:
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)
您的代码仅运行 rnorm(mean = c(5, 100, 900), sd = c(1, 2, 3), n = 9)
3 次并将其存储在列表.
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.
这篇关于purrr::pmap 与其他默认输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!