[英]purrr map instead of apply
I'm trying to incorporate more pipes in my code.我正在尝试在我的代码中加入更多的管道。 Oftentimes, I have to break up pipes to use the apply function.
通常,我必须打破管道才能使用 apply 函数。 Then I found purrr.
然后我发现了purrr。 However, it's not clear to me how exactly it works.
但是,我不清楚它究竟是如何工作的。 Here is what I want, and what I've tried.
这是我想要的,也是我尝试过的。 The main problem is that I want a rowwise computation.
主要问题是我想要一个 rowwise 计算。
want:想:
apply(mtcars,1,function(x) which.max(x))
have:有:
mtcars %>% map_dbl(which.max)
If we need rowwise, then use pmap
.如果我们需要 rowwise,则使用
pmap
。 According to ?pmap
根据
?pmap
... Note that a data frame is a very important special case, in which case pmap() and pwalk() apply the function .f to each row.
... 请注意,数据框是一个非常重要的特殊情况,在这种情况下, pmap() 和 pwalk() 将函数 .f 应用于每一行。 map_dfr(), pmap_dfr() and map2_dfc(), pmap_dfc() return data frames created by row-binding and column-binding respectively.
map_dfr()、pmap_dfr() 和 map2_dfc()、pmap_dfc() 分别返回由行绑定和列绑定创建的数据帧。 ...
...
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
Also, in base R
, this can be easily done and efficiently done with max.col
此外,在
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
The map
is used similar to lapply/sapply
where it loops through each column and apply the function on that column. map
的使用类似于lapply/sapply
,它循环遍历每一列并将函数应用于该列。 So, it would be similar to所以,这将类似于
apply(mtcars, 2, which.max)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.