Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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). 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...??? How to get 2015-03-31 instead?

like image 545
chengcj Avatar asked Oct 31 '22 01:10

chengcj


1 Answers

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.

like image 179
MrFlick Avatar answered Nov 09 '22 11:11

MrFlick