plevy
plevy

Reputation: 11

How should I use the as.POSIXlt function within a data.table?

In R, I'm trying to convert a POSIXct variable to a POSIXlt variable within a data table. For some reason this fails, though other type-conversion functions work.

library(data.table)
# make a sequence of dates
start_date <- as.POSIXct(strptime("01/01/2016", "%d/%m/%Y"), tz = "UTC")
end_date   <- as.POSIXct(strptime("10/01/2016", "%d/%m/%Y"), tz = "UTC")
n_times <- 10  # number of time points
datect <- seq(start_date, end_date, length = n_times)
datect

# put these in a data frame
df <- data.frame(datect = datect)
# and a data table
dt <- as.data.table(df)

Converting this to POSIXlt works fine within a data frame:

df$datelt <- as.POSIXlt(df$datect)

but fails in a data table:

dt$datelt <- as.POSIXlt(dt$datect)

Error in set(x, j = name, value = value) : 
  Supplied 9 items to be assigned to 10 items of column 'datelt'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

Other functions work ok, such as converting to a character or

dt$datech <- as.character(dt$datect)
dt$datech <- as.numeric(dt$datect)

Can anyone tell me why?

Upvotes: 1

Views: 22

Answers (0)

Related Questions