R翻阅副本&;选择

R翻阅副本&;选择,r,dataframe,R,Dataframe,我有这样一个数据框: id date amt 1 2012-05-03 10:33 32 2 2012-06-01 12:49 242 2 2012-06-05 00:09 43 3 2012-06-03 05:19 323 3 2012-06-08 08:45 12 4 2012-06-09 12:38 32 5 2012-06-09 10:31 53 现在我想删除重复的id,以便选择日期最早的一个。重复条目的数量各不相同

我有这样一个数据框:

id date               amt
1  2012-05-03 10:33   32
2  2012-06-01 12:49   242
2  2012-06-05 00:09   43
3  2012-06-03 05:19   323
3  2012-06-08 08:45   12
4  2012-06-09 12:38   32
5  2012-06-09 10:31   53
现在我想删除重复的
id
,以便选择日期最早的一个。重复条目的数量各不相同。我只关心每个特定的
id
和相应的
amt
的第一次出现,所有其他条目都应该删除


我知道如何使用循环实现这一点,但我觉得R中可以有一个简短而优雅的解决方案。

尝试类似
newdata的方法,使用
data.table
尝试类似
newdata的方法,以获得优雅的语法

library(data.table)

 datetime <- seq(as.POSIXct("2001-01-01"), as.POSIXct("2001-01-30"), l=7)    

DT <- data.table(id = c(1,2,2,3,3,4,5),x = datetime, amnt = sample(7))
DT
##    id                   x amnt
## 1:  1 2001-01-01 00:00:00    3
## 2:  2 2001-01-05 20:00:00    4
## 3:  2 2001-01-10 16:00:00    1
## 4:  3 2001-01-15 12:00:00    5
## 5:  3 2001-01-20 08:00:00    7
## 6:  4 2001-01-25 04:00:00    6
## 7:  5 2001-01-30 00:00:00    2

DT[, .SD[which.min(x)],by=id]
##    id                   x amnt
## 1:  1 2001-01-01 00:00:00    3
## 2:  2 2001-01-05 20:00:00    4
## 3:  3 2001-01-15 12:00:00    5
## 4:  4 2001-01-25 04:00:00    6
## 5:  5 2001-01-30 00:00:00    2
库(data.table)

datetime使用
data.table
实现优雅的语法

library(data.table)

 datetime <- seq(as.POSIXct("2001-01-01"), as.POSIXct("2001-01-30"), l=7)    

DT <- data.table(id = c(1,2,2,3,3,4,5),x = datetime, amnt = sample(7))
DT
##    id                   x amnt
## 1:  1 2001-01-01 00:00:00    3
## 2:  2 2001-01-05 20:00:00    4
## 3:  2 2001-01-10 16:00:00    1
## 4:  3 2001-01-15 12:00:00    5
## 5:  3 2001-01-20 08:00:00    7
## 6:  4 2001-01-25 04:00:00    6
## 7:  5 2001-01-30 00:00:00    2

DT[, .SD[which.min(x)],by=id]
##    id                   x amnt
## 1:  1 2001-01-01 00:00:00    3
## 2:  2 2001-01-05 20:00:00    4
## 3:  3 2001-01-15 12:00:00    5
## 4:  4 2001-01-25 04:00:00    6
## 5:  5 2001-01-30 00:00:00    2
库(data.table)

datetime是,如果日期已排序。是,如果日期已排序。