res group code value 1 1 1 0.3-6ren">
gpt4 book ai didi

r - data.table:表中所有现有组合的总和

转载 作者:行者123 更新时间:2023-12-05 01:37:15 25 4
gpt4 key购买 nike

我有一个数据表 out像这样(实际上它要大得多):

out <-      code weights group
1: 2 0.387 1
2: 1 0.399 1
3: 2 1.610 1
4: 3 1.323 2
5: 2 0.373 2
6: 1 0.212 2
7: 3 0.316 3
8: 2 0.569 3
9: 1 0.120 3
10: 1 0.354 3

它有 3 个不同代码的组(第 1 列)。在第 1 组中,代码 3 没有出现,而在另一组中出现。

然后,我想对每个组和代码组合的权重求和。我用这个命令实现了这一点:
sum.dt <- out[,.(sum(weights)), by=list(code,group)][order(-V1)]

这很有效,但它没有将组 1 与代码 3 组合在一起,因为它不在 out 中。 table 。我想在 sum.dt 中包含所有可能的组合,如果源表中没有出现该组合,则总和应为 0,即 V1 列在这一行中应该是 0。

知道我如何实现这一目标吗?

最佳答案

使用 CJ (交叉连接)您可以添加缺少的组合:

library(data.table)
setkey(out, code, group)
out[CJ(code, group, unique = TRUE)
][, lapply(.SD, sum), by = .(code, group)
][is.na(weights), weights := 0]

给出:

   code group weights
1: 1 1 0.399
2: 1 2 0.212
3: 1 3 0.474
4: 2 1 1.997
5: 2 2 0.373
6: 2 3 0.569
7: 3 1 0.000
8: 3 2 1.323
9: 3 3 0.316


或与 xtabs正如@alexis_laz 在评论中显示的那样:
xtabs(weights ~ group + code, out)

这使:

     code
group 1 2 3
1 0.399 1.997 0.000
2 0.212 0.373 1.323
3 0.474 0.569 0.316


如果你想在一个长格式的数据帧中得到这个输出,你可以包装 xtabs melt 中的代码reshape2(或data.table)包的功能:
library(reshape2)
res <- melt(xtabs(weights ~ group + code, out))

这使:

> class(res)
[1] "data.frame"
> res
group code value
1 1 1 0.399
2 2 1 0.212
3 3 1 0.474
4 1 2 1.997
5 2 2 0.373
6 3 2 0.569
7 1 3 0.000
8 2 3 1.323
9 3 3 0.316


你也可以结合 dplyr 和 tidyr 来做到这一点:
library(dplyr)
library(tidyr)
out %>%
complete(code, group, fill = list(weights=0)) %>%
group_by(code, group) %>%
summarise(sum(weights))

关于r - data.table:表中所有现有组合的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36175391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com