Ordered way to replicate reshape2 aggregation with tidyverse functions

I understand that by design , tidyr

it does less reshape2

: it tidyr

never merges.

Is there a "right" way to replicate aggregation reshape2

in the sense of better following the tidyverse philosophy?

I usually combine several dplyr verbs and then one of the tidyr. I.e:.

To replicate

dcast(mtcars, gear~cyl, value.var = "disp", sum)

  gear     4     6      8
1    3 120.1 483.0 4291.4
2    4 821.0 655.2    0.0
3    5 215.4 145.0  652.0

      

You can do

mtcars %>% 
    group_by(gear, cyl) %>% 
    summarise(disp = sum(disp)) %>% 
    spread(cyl, disp)

Source: local data frame [3 x 4]
Groups: gear [3]

   gear   `4`   `6`    `8`
* <dbl> <dbl> <dbl>  <dbl>
1     3 120.1 483.0 4291.4
2     4 821.0 655.2     NA
3     5 215.4 145.0  652.0

      

I would be grateful if this is the best solution, and if not, what will be better and why

+3


source to share





All Articles