purrr map instead of apply

Viewed 239

I'm trying to incorporate more pipes in my code. Oftentimes, I have to break up pipes to use the apply function. Then I found 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.

want:

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

have:

mtcars %>% map_dbl(which.max) 
1 Answers

If we need rowwise, then use pmap. According to ?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. map_dfr(), pmap_dfr() and map2_dfc(), pmap_dfc() return data frames created by row-binding and column-binding respectively. ...

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

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. So, it would be similar to

apply(mtcars, 2, which.max)
Related