如何对一个变量进行分组并根据另一个变量进行计数?
是否可以使用group_by对一个变量进行分组并根据另一个变量对目标变量进行计数? 例如,
x1 | x2 | x3 |
---|---|---|
A | 1 | 0 |
B | 2 | 1 |
C | 3 | 0 |
B | 1 | 1 |
A | 1 | 1 |
我想对 x3 的 0 和 1 进行计数,其中 x1
x1 | x3=0 | x3=1 |
---|---|---|
A | 1 | 1 |
B | 0 | 2 |
C | 1 | 0 |
是是否可以使用 group_by 并添加一些内容来总结?我尝试了 group_by x1 和 x3,但这将 x3 作为第二列,这不是我们正在寻找的。
如果不可能只使用group_by,我想我们可以对x1和x3进行group_by,然后按x3分割并cbind它们,但是分割后的两个数据帧具有不同的行长度,并且没有cbind_fill。我应该做什么来绑定它们并填补额外的空白?
Is it possible to use group_by to group one variable and count the target variable based on another variable?
For example,
x1 | x2 | x3 |
---|---|---|
A | 1 | 0 |
B | 2 | 1 |
C | 3 | 0 |
B | 1 | 1 |
A | 1 | 1 |
I want to count 0 and 1 of x3 with grouped x1
x1 | x3=0 | x3=1 |
---|---|---|
A | 1 | 1 |
B | 0 | 2 |
C | 1 | 0 |
Is it possible to use group_by and add something to summarize? I tried group_by both x1 and x3, but that gives x3 as the second column which is not what we are looking for.
If it's not possible to just use group_by, I was thinking we could group_by both x1 and x3, then split by x3 and cbind them, but the two dataframes after split have different lengths of rows, and there's no cbind_fill. What should I do to cbind them and fill the extra blanks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 data.table 包:
using the data.table package:
使用
dplyr::count
+tidyr::pivot_wider
实现所需结果的tidyverse
方法:DATA
A
tidyverse
approach to achieve your desired result usingdplyr::count
+tidyr::pivot_wider
:DATA
是的,这是可能的。这是一个例子:
Yes, it is possible. Here is an example: