我遇到了一个非常简单的data.table查询,但我无法弄明白!非常感谢您的帮助! 说我有这个R data.table:
dt <- data.table("ID"=c(1,1,2,2,2,3,4,5), "colour" = c("red","blue","red","blue","green","yellow","red","blue"), "timeinteam" = c(1,2,1,2,3,1,4,2))
ID colour timeinteam
1: 1 red 1
2: 1 blue 2
3: 2 red 1
4: 2 blue 2
5: 2 green 3
6: 3 yellow 1
7: 4 red 4
8: 5 blue 2
如果我想知道最长时间内哪个团队(颜色)是哪个ID,我该如何在data.table中这样做?我试过了:
dt[,.(Maxtimeinteam=max(timeinteam)), by=ID]
ID Maxtimeinteam
1: 1 2
2: 2 3
3: 3 1
4: 4 4
5: 5 2
这将为我提供每个ID的最长时间,但通过这样做,我将丢失有关属于该最大时间的颜色的信息。我想得到的结果是:
ID colour timeinteam
1 blue 2
2 green 3
3 yellow 1
4 red 4
5 blue 2