How do I achieve row-wise iteration using purrr::map?
Here\'s how I\'d do it with a standard row-wise apply.
df <- data.frame(a = 1:10, b = 11:20, c
Note that you're using only vectorized operations in your example so you could very well do :
df %>% dplyr::transmute(var1 = a+b,var2 = c/2)
(or in base R: transform(df,var1 = a+b,var2 = c/2)[4:5]
)
If you use non vectorized functions such as median you can use pmap
as in @aosmith 's answer, or use dplyr::rowwise
.
rowwise
is slower and the package maintainers advise to use the map
family instead, but it's arguably easier on the eye than pmap
in some cases. I personally still use it when speed isn't an issue:
library(dplyr)
df %>% transmute(var3 = pmap(.,~median(c(..1,..2,..3))))
df %>% rowwise %>% transmute(var3 = median(c(a,b,c)))
(to go back to a strict unnamed list output : res %>% split(seq(nrow(.))) %>% unname
)