我有一个日期时间列作为字符存储在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()
应该可行。
感谢您的任何想法。