R, issue with sqldf: cannot make condition on date

隐身守侯 提交于 2019-12-25 04:48:08

问题


I have a R dataframe with a field date (type date), i want to query this dataframe using sqldf library, but the where condition doesn't seem to work on the date field.

The query I'm using is:

sqldf("select * from  elog where 
      date >= '1997-01-01'
      limit 6")

It returns me an empty dataframe even though 'elog' has lines having 1997-01-01 as date


回答1:


You could try the same command after loading library(RH2)

library(RH2)
library(sqldf)
sqldf("select * from elog where
         date >= '1997-01-01' 
         limit 6")
#        date
#1 1997-01-01
#2 1997-07-01
#3 1998-01-01
#4 1998-07-01
#5 1999-01-01
#6 1999-07-01

Or without it, you may need to feed the numeric value as @bergant indicated in the comments

as.numeric(as.Date('1997-01-01'))
#[1] 9862
 sqldf("select * from elog
        where date >= 9862
        limit 6")
 #       date
 #1 1997-01-01
 #2 1997-07-01
 #3 1998-01-01
 #4 1998-07-01
 #5 1999-01-01
 #6 1999-07-01

the same using sprintf (@bergant's code)

 sqldf(sprintf("select * from elog 
       where date >= %d limit 6",
        as.Date('1997-01-01')))
 #       date
 #1 1997-01-01
 #2 1997-07-01
 #3 1998-01-01
 #4 1998-07-01
 #5 1999-01-01
 #6 1999-07-01

data

set.seed(42)
elog <- data.frame(date = seq(as.Date('1996-01-01'), 
           length.out=20, by='6 month', value=rnorm(20)) )



回答2:


Another similar alternative:

elog$newdate <- as.character(elog$date)
sqldf("select date from elog where
         newdate >= '1997-01-01' 
         limit 6")


来源:https://stackoverflow.com/questions/30936017/r-issue-with-sqldf-cannot-make-condition-on-date

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