假设我有一个像这样的data.table
sample<-data.table(id=c(1,1,2,2,3,3,3,4,4),
name=c("apple","apple","orange","orange",
"pear","pear","pear","banana","banana"),
atr=c("pretty","ugly","bruised","delicious",
"pear-shaped","bruised","infested",
"too-ripe","perfect"),
N=c(10,9,15,4,5,7,7,4,12))
我希望返回基本上独特的
unique(sample[,list(id, name)])
,但我还想要具有最大N值的atr
列的值。在最高N值存在平局的情况下,我不关心选择哪个,但只想选择一个。这个几乎可以工作:
merge(sample[,list(N=max(N)),by=list(id,name1)], sample,by=c("id","name1","N"))
,但由于pear有两个atr
值与最大值相等,因此会返回两个pear。除了没有给出预期结果之外,我还假设/希望有一种方法可以不涉及连接来完成这个问题。
sample[,{x<-atr[N==max(N)]; if(length(x)>1) x else *case of tie action*},by=.(id,name)]
的操作。 - MichaelChiricowhich.max
获取第一个匹配项,对吧?atr = atr[which.max(N)]
- Frank