如何在 purrr map 中传递数据帧和不均匀向量作为参数

sca*_*der 3 r dplyr purrr

我有一个混合数据类型的函数。它需要一个数据框和字符串变量作为输入参数。


library(dplyr)


myfunc <- function (dat=NULL,species=NULL,sepal_thres=NULL) {
 dat %>% 
    filter(Species==species & Sepal.Length <= sepal_thres) 

}

myfunc(dat=iris,species="virginica",sepal_thres=5)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1          4.9         2.5          4.5         1.7 virginica
Run Code Online (Sandbox Code Playgroud)

但我想将它与向量列表一起应用

species_vecs <- c("virginica","setosa")
sepal_thres_vecs <- c(5, 6)
purrr::pmap(list(dat=iris, species=species_vecs, sepal_thres=sepal_thres_vecs), myfunc)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Error: Element 2 has length 2, not 1 or 5.
Run Code Online (Sandbox Code Playgroud)

正确的做法是什么?

并不是从这个组合中获取speciessepal_tres参数:

 > expand.grid(species_vecs,sepal_thres_vecs) %>% rename(species=Var1, sepal_thres=Var2)
    species sepal_thres
1 virginica           5
2    setosa           5
3 virginica           6
4    setosa           6
Run Code Online (Sandbox Code Playgroud)

dat因为参数是固定的。

aos*_*ith 6

pmap如果您将长度为 1 的元素作为更大列表的一部分,则将使用回收。在这种情况下,您可以iris作为完整列表中的列表元素传递,以将其用于每个物种-萼片组合。

请注意,pmap按照它们出现的顺序遍历具有多个值的列表元素。如果您想要物种和萼片向量的每个组合,pmap您需要创建并提供完整向量作为列表元素(即,您必须自己进行交叉)。

purrr::pmap(list(dat = list(iris), species = rep(species_vecs, 2), 
                 sepal_thres = rep(sepal_thres_vecs, each = 2) ), myfunc)

[[1]]
  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          4.9         2.5          4.5         1.7 virginica

[[2]]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1           4.9         3.0          1.4         0.2  setosa
2           4.7         3.2          1.3         0.2  setosa
3           4.6         3.1          1.5         0.2  setosa
4           5.0         3.6          1.4         0.2  setosa
5           4.6         3.4          1.4         0.3  setosa
6           5.0         3.4          1.5         0.2  setosa
...
Run Code Online (Sandbox Code Playgroud)