计算切换值的观察百分比
我有一个具有两个列的数据集。一列指示该组,每个组只有两个行。第二列代表类别。现在,我想计算每个组没有相同类别的百分比。因此,在第1和第2行中,在第3和第4行中的类别不一样。在提供的数据中,我将获得66.66%的百分比,因为类别的变化四倍,而两组则保持不变。
这是我的数据:
structure(list(Group = c("A", "A", "B", "B", "C", "C", "D", "D",
"E", "E", "F", "F"), Category = c(1L, 2L, 3L, 3L, 5L, 6L, 7L,
7L, 7L, 6L, 5L, 4L)), class = "data.frame", row.names = c(NA,
-12L))
到目前为止,我已经尝试了以下内容:
Data <- Data %>%
group_by(Group) %>%
count(n())
但是现在我不在最后一行中编写代码以获取所需百分比。有人可以在这里帮我吗?
I have a dataset that has two columns. One column indicates the group and each group has only two rows. The second column represents the category. Now I would like to count the percentage of each group not having the same category. So in row 1 and 2, the Category is not the same while in row 3 and 4 it is the same. In the provided data, I would get a percentage of 66.66% as four times the Category changes while it stays the same for two groups.
This is my data:
structure(list(Group = c("A", "A", "B", "B", "C", "C", "D", "D",
"E", "E", "F", "F"), Category = c(1L, 2L, 3L, 3L, 5L, 6L, 7L,
7L, 7L, 6L, 5L, 4L)), class = "data.frame", row.names = c(NA,
-12L))
I have tried the following so far:
Data <- Data %>%
group_by(Group) %>%
count(n())
But I don't now how to write the code in the last line to get my desired percentage. Could someone help me here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
base
带有tapply()
的解决方案:使用
dplyr
,您可以使用n_distinct()
来计数独特的值。A
base
solution withtapply()
:With
dplyr
, you could usen_distinct()
to count the number of unique values.要显示这两个类别,您可以使用以下代码:
输出:
To show it for both classes, you can use the following code:
Output:
使用基本r
-output
Using base R
-output