【发布时间】:2015-03-05 23:55:35
【问题描述】:
我有一个data.table,我想对其执行分组操作,但想保留空变量并使用不同的分组变量集。
一个玩具例子:
library(data.table)
set.seed(1)
DT <- data.table(
id = sample(c("US", "Other"), 25, replace = TRUE),
loc = sample(LETTERS[1:5], 25, replace = TRUE),
index = runif(25)
)
我想通过关键变量的所有组合(包括空集)找到index 的总和。这个概念类似于 Oracle SQL 中的“分组集”,这是我当前解决方法的一个示例:
rbind(
DT[, list(id = "", loc = "", sindex = sum(index)), by = NULL],
DT[, list(loc = "", sindex = sum(index)), by = "id"],
DT[, list(id = "", sindex = sum(index)), by = "loc"],
DT[, list(sindex = sum(index)), by = c("id", "loc")]
)[order(id, loc)]
id loc sindex
1: 11.54218399
2: A 2.82172063
3: B 0.98639578
4: C 2.89149433
5: D 3.93292900
6: E 0.90964424
7: Other 6.19514146
8: Other A 1.12107080
9: Other B 0.43809711
10: Other C 2.80724742
11: Other D 1.58392886
12: Other E 0.24479728
13: US 5.34704253
14: US A 1.70064983
15: US B 0.54829867
16: US C 0.08424691
17: US D 2.34900015
18: US E 0.66484697
是否有首选的“数据表”方式来完成此操作?
【问题讨论】:
-
如果你真的想要
data.table中的结果,你在这里做的很好。如果您只是要查看结果,表格格式(在边缘带有交叉分类变量)要好得多:stable <- tapply(DT$index,list(DT$id,DT$loc),sum); mstable <- rbind(cbind(stable,apply(stable,1,sum)),c(apply(stable,2,sum),sum(stable)))。顺便说一下,生成随机数据时请使用set.seed作为示例。 -
哦,实际上比这更简单,因为
addmargins有效:addmargins(stable) -
Oracle GROUPING SETS 可以由 data.table 高级函数完成,不需要内部结构,与您所做的类似。我建议填写该功能的功能请求。
-
只是为了记录,有一个开放的FR data.table#1377。你也可以在这个SO 和更通用的rollup.data.table 方法中找到
rollup通用函数示例。他们仍然没有直接回答分组集,所以我只是发表评论。
标签: r data.table