这里有一个用data.table
的一行代码的方法:
library(data.table)
setDT(df)[df[, .I[which.max(Value)], by=c("Name", "City")]$V1][, sum(Value), by=City]
输出
City V1
1: NY 6
2: DC 2
基础R
aggregate(Value ~ City, merge(aggregate(Value ~ Name + City, data=df, max), df, all.x=T), sum)
City Value
1 DC 2
2 NY 6
数据
df <- structure(list(
Name = c("Tom", "Tom", "Tom", "James", "James",
"Tony", "Tony"),
City = c("NY", "NY", "NY", "NY", "NY", "DC",
"DC"),
Value = c(1L, 2L, 4L, 1L, 2L, 1L, 2L)
),
class = "data.frame",
row.names = c(NA, -7L))