R: Date function in sqldf giving unusual answer (wrong date format?)

南笙酒味 提交于 2019-11-28 10:28:42

问题


I am trying to add to a date using sqldf, i know it should be simple but I can't figure out what is wrong with my date format. Using:

sqldf("select date(model_date, '+1 day') from lapse_test")

give's answers like '-4666-01-23'

The model_date's are in the date format and look like 2015-01-01

I previously made them from a character string ('12/1/2015') using

lapse_test$model_date <- as.Date(lapse_test$date1,format = "%m/%d/%Y") or
lapse_test$model_date <- as.POSIXCT(lapse_test$date1,format = "%m/%d/%Y")

I'm guessing this is the problem? Any ideas?


回答1:


Passing a character variable to the date() function seems to work:

df <- data.frame(a=as.Date("2010-10-01"))
df$b <- as.character(df$a)

sqldf("select date(a) from df")
#       date(a)
# 1 -4672-08-24

sqldf("select date(b) from df")
#      date(b)
# 1 2010-10-01

sqldf("select date(b, '+1 day') from df")
#   date(b, '+1 day')
# 1        2010-10-02

Note that you can do (some) arithmetic on Date objects in R directly, without needing SQL:

df$a <- df$a + 1
df
#            a          b
# 1 2010-10-02 2010-10-01



回答2:


SQLite date functions consider dates as days since Nov 24, 4714BC, which means the integer storage of 16770 for the example date of 2015-12-01 in R returns an ancient date somewhere in 4667BC.

You can figure out that the difference between the R origin of 1970-01-01 and the SQLite origin is 2440588 days. Which means, you can take this constant into account if you want:

test <- data.frame(model_date=as.Date("12/1/2015",format="%m/%d/%Y"))
sqldf("select date(model_date + 2440588, '+1 day') as select_date from test")
#  select_date
#1  2015-12-02

@HongOoi's answer is probably better, but I thought this might be interesting to know the underlying workings.



来源:https://stackoverflow.com/questions/39241030/r-date-function-in-sqldf-giving-unusual-answer-wrong-date-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!