How to get last data for each id/date?

前端 未结 3 1807
予麋鹿
予麋鹿 2020-12-11 12:30

I have a data frame that contains id, POSIXct(Date & Time)

> myData

   Tpt_ID    Tpt_DateTime               Value
1  1         2013-01-01 15:17:21 C         


        
3条回答
  •  庸人自扰
    2020-12-11 13:05

    Another data.table solution, which works in a manner similar to @SimonO101's answer -

    library(data.table)
    dt <- data.table( dt )
    dt[ , Date:= as.Date( Tpt_DateTime ) ]
    
    #indexing the data.table
    setkey(dt,Tpt_ID,Date)
    #mult = "last" returns te last row of each unique group as defined by the by argument
    dt[dt[unique(dt), mult="last", which=TRUE]]
    

    This returns -

    > dt[dt[unique(dt),,mult="last", which=TRUE]]
       Tpt_ID        Tpt_DateTime Value       Date
    1:      1 2013-01-01 16:47:21    21 2013-01-01
    2:      1 2013-01-02 12:40:11    15 2013-01-02
    3:      2 2013-01-01 12:48:32     5 2013-01-01
    4:      2 2013-02-02 17:48:32     8 2013-02-02
    5:      3 2013-01-01 13:30:02     1 2013-01-01
    6:      3 2013-02-03 19:30:02     3 2013-02-03
    

提交回复
热议问题