我认为 Owe Jessen 的评论是正确的,这不是问题的答案。这是我在data.table 的帮助下拍摄的照片。
首先,让我们使用一个更容易理解的例子:
library(data.table)
DT <- data.table(AccountID = rep(1:3, each=4),
V1 = sample(1:100, 12, replace=FALSE),
Month = rep(1:4, times=3))
AccountID V1 Month
[1,] 1 81 1
[2,] 1 23 2
[3,] 1 72 3
[4,] 1 36 4
[5,] 2 22 1
[6,] 2 13 2
[7,] 2 50 3
[8,] 2 40 4
[9,] 3 74 1
[10,] 3 83 2
[11,] 3 4 3
[12,] 3 3 4
所以这里我们有 3 个帐户和 4 个月,对于每个帐户/月份组合,我们都有一个 V1。因此,为了找到每个帐户的最大 V1,我执行以下操作:
setkey(DT, AccountID)
DT <- DT[, list(maxV1=max(V1)), by="AccountID"][DT]
DT[maxV1==V1]
AccountID maxV1 V1 Month
[1,] 1 81 81 1
[2,] 2 50 50 3
[3,] 3 83 83 2
这有点难以理解,所以我试着解释一下:我将 AccountID 设置为 DT 的 key。现在,我基本上在DT[, list(maxV1=max(V1)), by="AccountID"][DT] 中做了两个步骤。首先,我计算每个帐户的最大 V1 值 (DT[, list(maxV1=max(V1)), by="AccountID"]),然后通过紧跟其后调用 [DT],将这个新列 maxV1 添加到旧的 DT。显然,那么我只需要获取 maxV1==V1 持有的所有行。
将此解决方案应用于 Nico 更高级的示例,并向您展示如何将 data.frame 转换为 data.table:
library(data.table)
DT <- as.data.table(m)
#Note that this line is only necessary if there are more than one rows per Month/AccountID combination
DT <- DT[, sum(V1), by="Month,AccountID"]
setkey(DT, AccountID)
DT <- DT[, list(maxV1=max(V1)), by="AccountID"][DT]
DT[maxV1==V1]
AccountID maxV1 Month V1
1 24660 1 24660
2 22643 2 22643
3 23642 3 23642
4 22766 5 22766
5 22445 12 22445
...
这正好给出了 50 行。
编辑:
这是一个 base-R 解决方案:
df <- data.frame(AccountID = rep(1:3, each=4),
V1 = sample(1:100, 12, replace=FALSE),
Month = rep(1:4, times=3))
df$maxV1 <- ave(df$V1, df$AccountID, FUN = max)
df[df$maxV1==df$V1, ]
我的灵感来自here。