Simple question. I'd like to use pivot_wider on a dataset to count the number of occurrences of each category:
Here is an example with the data mtcars (where I group them by cyl, and then count up the occurrences of the different carbs)
mtcars %>%
dplyr::group_by(cyl,carb) %>%
dplyr::summarize(sum=n()) %>%
pivot_wider(id_cols="cyl",names_from="carb",values_from="sum")
# A tibble: 3 x 7
# Groups: cyl [3]
cyl `1` `2` `4` `6` `3` `8`
<dbl> <int> <int> <int> <int> <int> <int>
1 4 5 6 NA NA NA NA
2 6 2 NA 4 1 NA NA
3 8 NA 4 6 NA 3 1
Is there a way for me to do this directly with 'pivot_wider'? I can do this with 'dcast'
mtcars %>%
dcast(cyl~carb,fun.aggregate=length)
Using carb as value column: use value.var to override.
cyl 1 2 3 4 6 8
1 4 5 6 0 0 0 0
2 6 2 0 0 4 1 0
3 8 0 4 3 6 0 1
...but I like using 'pivot_wider' for a lot of other things (its syntax makes sense to me).
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…