本文介绍了如何将数据框和不均匀向量作为Purrr映射中的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function with mixed data types. It takes a data frame and string variable as the input parameter.




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

但是我想将其与载体列表一起应用

But I want to apply it with list of vectors

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.

执行此操作的正确方法是什么?

What's the right way to do it?

不是 sepal_tres 参数是从以下组合中获取的: / p>

Not that the species and sepal_tres parameters are taken from this combination:

 > 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 将使用回收一个length-1元素,作为更大列表的一部分。在这种情况下,您可以将 iris 作为完整列表中的列表元素传递,以将其用于每个物种-种皮组合。

pmap will use recycling if you have a length-1 element as part of your bigger list. In this case, you can pass iris as a list element within the full list to use it for each species-sepal combination.

请注意, pmap 会按顺序显示具有多个值的列表元素。如果要在 pmap 中将物种和萼片向量的每种组合,都需要创建并提供完整的向量作为列表元素(即,您必须自己进行交叉)

Note that pmap goes through list elements with multiple values in the order they appear. If you want every combination of the species and sepal vectors in pmap you would need to create and give the full vectors as list elements (i.e., you would have to do the crossing yourself).

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

这篇关于如何将数据框和不均匀向量作为Purrr映射中的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 13:16