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

标签 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

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

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)

我收到了这个错误:

Error: Element 2 has length 2, not 1 or 5.

正确的做法是什么?

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

但是 dat 作为参数是固定的。

最佳答案

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
...

关于r - 如何在 purrr map 中传递数据帧和不均匀向量作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902461/

相关文章:

r - 计算 df 中每个元素的百分比值(基于最大值);但是在指定的列中

r - 按属性对网络节点进行聚类

r - 如何选择具有等于或超过 2 个唯一值的列,同时忽略 NA 和空白?

r - 如何对宽 R 数据框中的列和行求和?

r - 在 R 中使用 map() rowise

r - 子集 1 列矩阵删除行名

r - forestplot 在图中有异常大的蓝点

r - 在 R dplyr 中按计数展开列

r - 在 data.frame 上使用 invoke_map() 或 exec()

r - 提取模型摘要并将其存储为新列