1

我有一个日期时间列作为字符存储在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()应该可行。

感谢您的任何想法。

4

2 回答 2

4

@SymbolixAU 在评论中已经很好地回答了。
解决您关于 data.frame/data.frame 差异的问题。
主要区别在于它POSIXlt需要更多的内存POSIXct,而 data.table 确实关心内存。

object.size(Sys.time())
#312 bytes
object.size(as.POSIXlt(Sys.time()))
#2144 bytes

重要的是要知道您仍然可以POSIXlt在 data.table 参数中使用数据类型(及其方法)j,只需确保POSIXct在分配给列时将其转换为。

如果出于某种原因您想将 POSIXlt 存储在 data.table 中...data.table不支持与 data.frame 相同的 POSIXlt 类型。您可以将 POSIXlt 存储在 data.table 中,但只需将其包装到列表中,就像任何其他非原子数据类型一样。

于 2016-08-29T08:47:06.040 回答
1

和类似的东西

data.table(as.Date(date_chr))
于 2018-05-21T08:58:49.313 回答