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

前端 未结 2 1069

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(mo         


        
2条回答
  •  -上瘾入骨i
    2020-12-21 22:49

    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
    

提交回复
热议问题