R reshape 数据框以获得观察的出现总数

标签 r reshape

我正在考虑如何 reshape 这样的数据框:

id type points times
1   A    3       1
2   B    3       2
3   A    3       3
4   B    2       4
5   A    1       5

对此:

points   A    B
1        5    0
2        0    4
3        4    2

所以,我想将点和类型作为列,统计某个点在所有类型中出现的总数。

最佳答案

您可以使用 reshape2 中的 dcast

reshape2::dcast(dat[-1], points ~ type, fill = 0, fun.aggregate = sum)
#  points A B
#1      1 5 0
#2      2 0 4
#3      3 4 2

或者没有外部包,您可以使用xtabs

xtabs(times ~ points + type, data = dat)
#      type
#points A B
#     1 5 0
#     2 0 4
#     3 4 2

关于R reshape 数据框以获得观察的出现总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55854805/

相关文章:

r - ggplot2 堆叠条形图顺序在更新后中断

r - 使用多个条件在 RStudio 中过滤 "is not equal to"

r - R 中用另一个矩阵求子集

mysql - 在 MySQL 或 R 中 reshape 表

r - 如何有选择地将列转换为 data.frame 中的行?

r - 嵌套 ifelse 条件顺序不同的不同结果

r - 函数对象的属性是什么/在哪里?

R 从短格式转换为长格式,并以短格式计数

将二项式数据 reshape 为长伯努利格式

r - 带强制转换的自动列名称标签