pivot_wider,计数出现次数 [英] pivot_wider, count number of occurrences
问题描述
简单的问题.我想在数据集上使用 pivot_wider 来计算每个类别的出现次数:
Simple question. I'd like to use pivot_wider on a dataset to count the number of occurrences of each category:
这是一个包含数据 mtcars 的示例(我将它们按 cyl 分组,然后计算不同碳水化合物的出现次数)
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
有没有办法让我直接使用pivot_wider"来做到这一点?我可以用'dcast'来做到这一点
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
...但我喜欢将pivot_wider"用于其他很多事情(它的语法对我来说很有意义).
...but I like using 'pivot_wider' for a lot of other things (its syntax makes sense to me).
谢谢!
推荐答案
您可以将 values_fn
参数用于 pivot_wider
,其作用与 fun 相同.aggregate
在 dcast 中.
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))
请注意,您必须选择一列(我随意选择了am
),然后将values_fn
作为命名列表(假设您想取其长度)柱子).这是一个命名列表,因为在其他用例中,您可能会聚合多个列.
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.
这篇关于pivot_wider,计数出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!