简体   繁体   English

使用R中的data.table将POSIXct列连接到Date列

[英]Joining a POSIXct column to Date column using data.table in R

In the following example, can someone explain to me why the date 2015-03-31 changed to 1034-04-03? 在以下示例中,有人可以向我解释为什么2015-03-31的日期更改为1034-04-03?

dt1 = data.table(id = c(1,2), date = as.POSIXct("2015-03-31 BST"), key = "id")
dt1
#    id       date
# 1:  1 2015-03-31
# 2:  2 2015-03-31
dt2 = data.table(id = c(1,2), date = as.Date(NA), key = "id")
dt2
#    id date
# 1:  1 <NA>
# 2:  2 <NA>
dt2[dt1, date := i.date]
dt2
#    id       date
# 1:  1 1034-04-03
# 2:  2 1034-04-03

My aim is to get date from dt1 to dt2 in Date format instead of POSIXct by id (different id would have different date ). 我的目的是让datedt1dt2Date格式,而不是POSIXctid (不同的id会有不同的date )。 How would I do that? 我该怎么办?

Following is what I want: 以下是我想要的:

dt2
#    id       date
# 1:  1 2015-03-31
# 2:  2 2015-03-31

EDIT : 编辑

I've tried the following: 我尝试过以下方法:

dt2[dt1, date := as.Date(i.date)]
dt2
#    id       date
# 1:  1 2015-03-30
# 2:  2 2015-03-30

Unfortunately, it is giving me 2015-03-30 instead of 2015-03-31...??? 不幸的是,它给了我2015-03-30而不是2015-03-31 ... ??? How to get 2015-03-31 instead? 如何获得2015-03-31?

You can use 您可以使用

dt2[dt1, date:=as.Date(i.date)]

You might want to also see the question Convert column classes in data.table about changing data types in data.tables. 您可能还希望在data.table中看到有关更改data.tables中的数据类型的转换列类的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM