我有两个分类列(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"
Run Code Online (Sandbox Code Playgroud)
另一种选择是排序C并仅提取唯一的B组.对于具有多个组的大数据集,这应该更快,因为它不计算每组的最大值,而是仅排序一次
unique(dt[order(-C)], by = "B")
# A B C
# 1: c d 3
Run Code Online (Sandbox Code Playgroud)