R purrr ::: pmap:如何按名称引用输入参数?

问题描述 投票:10回答:3

我正在使用R purrr:::pmap三个输入。目前尚不清楚我如何在公式调用中明确引用这些输入?使用map2时,公式调用为~ .x + .y。但是在使用pmap时该怎么做?

http://r4ds.had.co.nz/lists.html再现Hadley的例子

library(purrr)
mu <- list(5, 10, -3)
sigma <- list(1, 5, 10)
n <- list(1, 3, 5)

args2 <- list(mean = mu, sd = sigma, n = n)
pmap(args2, rnorm)

如果我想在调用rnorm时显式引用输入参数,我可以使用:

pmap(args2, function(mean, sd, n) rnorm(n, mean, sd))

但是说我想用公式方法做到这一点。我怎么做?例如,这不起作用:

pmap(args2, ~rnorm(n=.n, mean=.mean, sd=.sd))

谢谢!!

r purrr tidyverse
3个回答
8
投票

version 0.2.3你可以使用..1..2..3等:

pmap(args2, ~ rnorm(..3, ..1, ..2))

但是......我已经遇到了这种语法的问题,例如使用replicate

pmap(list(1, 2), ~ replicate(n = ..1, expr = ..2))
# Error in FUN(X[[i]], ...) : the ... list does not contain 2 elements

可能是因为:

print(replicate)
# function (n, expr, simplify = "array") 
#   sapply(integer(n), eval.parent(substitute(function(...) expr)), 
#          simplify = simplify)

似乎function(...) expr中的substitute()..2表现不佳,被解释为...的第二个元素,它是空的。

请注意,pmap(list(1, 2), ~ replicate(n = ..1, expr = .y))仍然有效。


5
投票

您可以使用with(...)来解决此问题:

pmap(args2, ~with(list(...),rnorm(n, mean, sd)))
# [[1]]
# [1] 2.733528
# 
# [[2]]
# [1] 4.0967533 6.4926143 0.6083532
# 
# [[3]]
# [1]  1.8836592 -0.2090425 -4.0030168  1.1834931  3.2771316

更多解释:Harnessing .f list names with purrr::pmap


3
投票

似乎pmap无法通过公式接口中的名称访问列表中的参数。您可以登记入住https://github.com/hadley/purrr/issues/203

例如,您可以这样做:

pmap(list(1:2, 5:6), ~ .x + .y)

因此,列表的第一个元素由.xand引用,第二个由.y引用。但是,如果您尝试将列表的参数命名为

pmap(list(a = 1:2, b =  5:6), ~ .a + .b)

然后你会有错误:

Error in .f(a = .l[[c(1L, i)]], b = .l[[c(2L, i)]], ...) : 
  unused arguments (a = .l[[c(1, i)]], b = .l[[c(2, i)]])

我认为在函数pmap的公式接口中,如果你想使用公式接口而不使用function(mean , sd, n),你可以做的最好的是:

  1. 不要列出列表中的元素
  2. 不要使用两个以上的参数(为了使用隐式名称.x.y

因此,你可以使用你想要的第三个参数n(例如n = 4)的值,然后运行:

mu <- list(5, 10, -3)
sigma <- list(1, 5, 10)
set.seed(1)
pmap(list(mu,sigma), ~ rnorm(mean = .x, sd = .y, n = 4))

哪个将返回:

[[1]]
[1] 4.373546 5.183643 4.164371 6.595281

[[2]]
[1] 11.647539  5.897658 12.437145 13.691624

[[3]]
[1]  2.7578135 -6.0538839 12.1178117  0.8984324

[[4]]
[1]  9.136278  4.355900 14.374793 10.865199
© www.soinside.com 2019 - 2024. All rights reserved.