purrr地图而不是套用

时间:2019-06-18 20:11:05

标签: r purrr

我正在尝试在我的代码中合并更多管道。经常,我必须拆开管道才能使用apply函数。然后我发现了purrr。但是,我不清楚它是如何工作的。这就是我想要的,也是我尝试过的。主要问题是我想要按行计算。

想要:

apply(mtcars,1,function(x) which.max(x))

拥有:

mtcars %>% map_dbl(which.max) 

1 个答案:

答案 0 :(得分:2)

如果需要按行,则使用pmap。根据{{​​1}}

  

...请注意,数据帧是非常重要的特殊情况,在这种情况下,pmap()和pwalk()将函数.f应用于每行。 map_dfr(),pmap_dfr()和map2_dfc(),pmap_dfc()分别返回通过行绑定和列绑定创建的数据帧。 ...

?pmap

此外,在pmap_int(mtcars, ~ which.max(c(...))) #[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 4 4 3 中,使用base R可以轻松,高效地完成此操作

max.col

max.col(mtcars, "first") #[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 4 4 3 的用法与map相似,在lapply/sapply中循环遍历每一列并在该列上应用函数。因此,它将类似于

apply(mtcars, 2, which.max)