Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pivot_wider, count number of occurrences

Tags:

r

tidyr

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!

like image 226
Andrew Avatar asked Jul 14 '26 04:07

Andrew


2 Answers

You can use the values_fn argument to pivot_wider, which plays the same role as fun.aggregate in dcast.

mtcars %>%
    pivot_wider(id_cols = "cyl",
                names_from = "carb",
                values_from = "am",
                values_fn = list(am = length))

Note that you have to pick a column (arbitrarily, I chose am), and give values_fn as a named list (saying you want to take the length of that column). It's a named list because in other use cases you could be aggregating multiple columns.

like image 79
David Robinson Avatar answered Jul 15 '26 18:07

David Robinson


I understand that you are looking for tidyr::pivot_wider answer but in this case you can use table to get your expected output.

with(mtcars,table(cyl, carb))

#    1 2 3 4 6 8
#  4 5 6 0 0 0 0
#  6 2 0 0 4 1 0
#  8 0 4 3 6 0 1
like image 33
Ronak Shah Avatar answered Jul 15 '26 17:07

Ronak Shah