ID <- c(1,1,1,2,2,2,2,3,3,3)
Value <- c(2,3,5,2,5,8,17,3,5,5)
Event <- c(1,1,2,1,2,1,2,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)
# 将数据从data frame格式转还成data.table格式
library(data.table)
group <- as.data.table(group)
最值在多行出现,容忍取出多行时
group[group[, .I[pt == max(pt)], 。(Subject,Event)]$V1]
如果最值在多行同时存在,但是要求只取出一行:
group[group[, .I[which.max(pt)], by=c("Subject","Event")]$V1]
p.s: by - c(“列名1”,“列名2”) 的效果和 .(“列名1”,“列名2”) 是一样的,详见知乎 data.table包整理贴
Reference: