Indexing dataframe by date interval

大兔子大兔子 提交于 2019-12-23 15:14:53

问题


I have a dataframe with one column that contains several hundreds of dates in Date format e.g.:

as.Date(c("2011-08-13","2011-09-13","2010-06-12","2012-09-13","2010-09-13","2012-05-26","2012-07-20"))

Now I'd like to select only the rows where 15.03 < date < 15.8 (all Dates between 15th march and 15th october, disregarding the year). Is there a simple way to select (index) in such a way?


I slightly modified the answer I accepted, as below:

a <- as.Date(c("2011-08-13","2011-09-13","2010-06-12","2012-09-13","2010-09-13","2012-05-26","2012-07-20"))
lower <- as.Date("03-15",format="%m-%d")
upper <- as.Date("08-15",format="%m-%d")
a[format(a,"%m-%d") < format(upper,"%m-%d") & format(a,"%m-%d") > format(lower,"%m-%d")]
[1] "2011-08-13" "2010-06-12" "2012-05-26" "2012-07-20"

回答1:


In base, the idea is to use function format:

a <- as.Date(c("2011-08-13","2011-09-13","2010-06-12","2012-09-13","2010-09-13","2012-05-26","2012-07-20"))
lower <- as.Date("2012-03-15")
upper <- as.Date("2012-08-15")
a[format(a,"%m-%d") < format(upper,"%m-%d") & format(a,"%m-%d") > format(lower,"%m-%d")]
[1] "2011-08-13" "2010-06-12" "2012-05-26" "2012-07-20"


来源:https://stackoverflow.com/questions/13911141/indexing-dataframe-by-date-interval

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