R,与sqldf的问题:不能在日期条件 [英] R, issue with sqldf: cannot make condition on date
本文介绍了R,与sqldf的问题:不能在日期条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的查询是:
sqldf(select * from elog where
date> ='1997-01-01'
limit 6)
它给我一个空的数据框,即使'elog'的行已经有了1997-01-01作为日期
解决方案
你可以尝试一样命令后加载库(RH2)
库(RH2)
库(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
否则,您可能需要将数字值指定为@bergant评论
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
使用 sprintf
(@ bergant的代码)
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
数据
set.seed )
elog< - data.frame(date = seq(as.Date('1996-01-01'),
length.out = 20,by ='6 months',value = rnorm (20)))
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
解决方案
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)) )
这篇关于R,与sqldf的问题:不能在日期条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文