对数据框进行双重聚合的有效方法
efficient way to double aggregation for a data frame
我有一个关于聚合数据帧两倍的问题,涉及重新格式化 table。
我有一个 table,包含两列:名称和类别。类别是因子变量,包含 10 个级别,例如“0”到“9”。所以数据框看起来像:
name category
a 0
a 1
a 1
a 4
a 9
b 2
b 2
b 2
b 3
b 7
b 8
c 0
c 0
c 0
我想要汇总的结果如下所示:
name category.0 category.1 category.2 category.3 category.4 ..... category.9
a 1 2 0 0 1 1
b 0 0 3 1 0 0
c 3 0 0 0 0 0
它计算每个唯一名称有多少个“0”、“1”、...、“9”。
我为生成结果所做的是使用一个简单的聚合函数
new_df <- aggregate(category ~ name,df, FUN=summary)
然后取消列出 new_df 的第二列以获得结果。
然而,它太慢了。我想知道是否有更有效的方法来做到这一点。
您可以使用包 reshape2
中的 dcast
:
library(reshape2)
x = dcast(df, name~category)
setNames(x, c(names(x)[1], paste0('category',names(x)[-1])))
# name category0 category1 category2 category3 category4 category7 category8 category9
#1 a 1 2 0 0 1 0 0 1
#2 b 0 0 3 1 0 1 1 0
#3 c 3 0 0 0 0 0 0 0
我有一个关于聚合数据帧两倍的问题,涉及重新格式化 table。
我有一个 table,包含两列:名称和类别。类别是因子变量,包含 10 个级别,例如“0”到“9”。所以数据框看起来像:
name category
a 0
a 1
a 1
a 4
a 9
b 2
b 2
b 2
b 3
b 7
b 8
c 0
c 0
c 0
我想要汇总的结果如下所示:
name category.0 category.1 category.2 category.3 category.4 ..... category.9
a 1 2 0 0 1 1
b 0 0 3 1 0 0
c 3 0 0 0 0 0
它计算每个唯一名称有多少个“0”、“1”、...、“9”。
我为生成结果所做的是使用一个简单的聚合函数
new_df <- aggregate(category ~ name,df, FUN=summary)
然后取消列出 new_df 的第二列以获得结果。
然而,它太慢了。我想知道是否有更有效的方法来做到这一点。
您可以使用包 reshape2
中的 dcast
:
library(reshape2)
x = dcast(df, name~category)
setNames(x, c(names(x)[1], paste0('category',names(x)[-1])))
# name category0 category1 category2 category3 category4 category7 category8 category9
#1 a 1 2 0 0 1 0 0 1
#2 b 0 0 3 1 0 1 1 0
#3 c 3 0 0 0 0 0 0 0