0

I would like to create a "timeID" column based on the another ID and the timestamp... I'm using data.table::setorder() and I'm most of the way there but timeID column is just populating with the timestamp value rather than a time ID (1,2,3,...n). Image is my current output...

enter image description here

What am I missing here?

# Parse timestamp
df1[, Month := str_sub(df1$BaseTimeStamp, 4,6)]
df1[, Year := str_sub(df1$BaseTimeStamp, 8,11)]
df1[, Day := str_sub(df1$BaseTimeStamp, 1,2)]
df1[, Hour := str_sub(df1$BaseTimeStamp, 13,14)]
df1[, Min := str_sub(df1$BaseTimeStamp, 16,17)]
df1[, Sec := str_sub(df1$BaseTimeStamp, 19,20)]
df1[, timeParse := ymd_hms(paste(df1$Year,
                                 df1$Month,
                                 df1$Day,
                                 df1$Hour,
                                 df1$Min,
                                 df1$Sec))]
# Create timeStamp ID
df1[, timeID := setorder(df1, myID, timeParse), by = myID]

Desired outcome would be... enter image description here

3
  • 2
    Not clear what values you're expecting here... df1[order(timeParse), v := 1:.N, by=myID]? Btw, str_sub is not the "right" way to extract those things. If you look at lubridate or data.table, there are functions like ?hour, ?month, etc
    – Frank
    Apr 26, 2018 at 17:15
  • I edited to add a bare-bones example of my desired outcome.
    – mikeLdub
    Apr 26, 2018 at 18:22
  • 1
    Ok. If your data is sorted by timeParse, then DT[, v := rowid(myID)] should work.
    – Frank
    Apr 26, 2018 at 18:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.