【发布时间】:2016-08-29 04:24:22
【问题描述】:
我有一个日期时间列作为字符存储在data.table 中。当我转换为 POSIXct 然后尝试四舍五入为仅日期时,我得到了奇怪的结果。
library(data.table)
library(lubridate)
# suppose I have these dates, in a data.table
date_chr <- c("2014-04-09 8:37 AM", "2014-09-16 6:04 PM",
"2014-09-30 3:26 PM", "2014-11-13 12:47 PM",
"2014-11-05 12:25 PM")
dat <- data.table(date_chr)
# I convert to POSIXct...
dat[, my_date := ymd_hm(date_chr)]
# ...and I want to round to date only, but this doesn't work
dat[, date_only := round(my_date, 'days')] # why does this return a list?
dat[, date_only := trunc(my_date, 'days')] # this too
class(dat$date_only) 是 list,我收到此警告消息
# Warning message:
# In `[.data.table`(dat, , `:=`(date_only, round(my_date, "days"))) :
# Supplied 9 items to be assigned to 5 items of column 'date_only' (4 unused)
同时,这工作正常!
dat_df <- data.frame(date_chr, stringsAsFactors = F)
dat_df$my_date <- ymd_hm(dat_df$date_chr)
dat_df$date_only <- round(dat_df$my_date, 'days')
class(dat_df$date_only) 是 POSIXlt, POSIXt,根据需要。
我的问题是,为什么会这样?使用data.table 时如何避免这个问题?有一些变通方法,比如在转换之前截断date_chr 的时间部分,但似乎round.POSIXt() 应该可以工作。
感谢您的任何想法。
【问题讨论】:
-
至 POSIXct:
dat[, my_date := as.POSIXct(date_chr, format = "%Y-%m-%d %I:%M")],仅限日期:dat[, date_only := as.Date(my_date, tz = "Australia/Melbourne")] -
当你使用
round.POSIXt()时,它会返回一个列表(见?round.POSIXt),即POSIXlt对象。 -
data.table出于性能原因不支持POSIXlt types -
@arvi1000 我已经扩展了答案以澄清在 data.table 中存储 POSIXlt 仍然是可能的,只是与在 data.frame 中的方式不同。
标签: r data.table lubridate posixct datetime-conversion