dplyr pivot table

主宰稳场 提交于 2019-12-06 07:25:38

We group by 'cyl', 'gear', get the frequency count (tally()), reshape from 'long' to 'wide' (using spread from tidyr), ungroup to remove the attributes (previously, it used to work without this), use mutate to create 'V1' as the sum of each row (using rowSums) and finally arrange (order) the rows based on values in 'V1'.

library(dplyr)
library(tidyr)

mtcars %>%
   group_by(cyl, gear) %>% 
   tally() %>%
   spread(gear, n, fill=0) %>% 
   ungroup() %>%
   mutate(V1= rowSums(.[-1])) %>% 
   arrange(desc(V1))
#    cyl     3     4     5    V1
#  <dbl> <dbl> <dbl> <dbl> <dbl>
#1     8    12     0     2    14
#2     4     1     8     2    11
#3     6     2     4     1     7
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!