Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

r - pivot_wider, count number of occurrences

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...