我有两个分类列(A,B)和数字列(C)。我想获得 A 的值,其中 C 是 B 定义的组的最大值。我正在寻找 data.table 解决方案。
library(data.table)
dt <- data.table( A = c("a","b","c"),
B = c("d","d","d"),
C = c(1,2,3))
dt
A B C
1: a d 1
2: b d 2
3: c d 3
# I want to find the value of A for the maximum value
# of C when grouped by B
dt[,max(C), by=c("B")]
B V1
1: d 3
#how can I get the A column, value = "c"
最佳答案
另一种选择是按 C
排序并提取唯一的 B
组。对于具有许多组的大数据集,这应该更快,因为它不计算每组的最大值,而只排序一次
unique(dt[order(-C)], by = "B")
# A B C
# 1: c d 3
关于r - 第二列的 data.table 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33043146/