JerryN
JerryN

Reputation: 2506

R round PosixCT variable in a data table

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.

Upvotes: 4

Views: 628

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26248

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"))]

Upvotes: 5

Related Questions