4

The following code creates a 10 row data table with one variable, timeStamp, in POSIXct format.

library(data.table)
dt <- data.table(timeStamp = seq( as.POSIXct("2017-07-01 14:51:50"), by=60, len=10))

I want to round timeStamp to the nearest minute.

This command puts a list in each row of timeStamp2 rather than modified POSIXct variables.

dt[, timestamp2 := round(timeStamp, "mins")]

The line of code below does what I want (round up in this example) but doesn't work within the data table.

timestamp2 <- round(dt$timeStamp, "mins")

I'm using data.table version 1.10.4-3 and MRAN R version 3.4.1.

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
JerryN
  • 2,356
  • 1
  • 15
  • 49
  • 3
    `?round.POSIXt` returns a `POSIXlt`. wrap it in `as.POSIXct()` : `dt[, timestamp2 := as.POSIXct(round(timeStamp, "mins"))]` – SymbolixAU Nov 21 '17 at 00:17
  • @SymbolixAU - that's the answer mate... bung it in the answer box below! – thelatemail Nov 21 '17 at 00:46
  • @thelatemail - I was kinda waiting for someone to find a duplicate for it... – SymbolixAU Nov 21 '17 at 01:00
  • @SymbolixAU, [this](https://stackoverflow.com/questions/11325631/round-a-posix-date-posixct-with-base-r-functionality) seems the closest match, but it doesn't clarify the POSIXlt element, so the answer has clear value! – Kevin Arseneau Nov 21 '17 at 01:12

1 Answers1

5

From ?round.POSIXt:

Value

An object of class "POSIXlt" or "Date".

Which means the result of round on a POSIX object is a POSIXlt object.

Therefore you need to wrap your round function inside as.POSIXct() to get it back to POSIXct

dt[, timestamp2 := as.POSIXct(round(timeStamp, "mins"))]
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139