Johannes
Johannes

Reputation: 1064

Indexing dataframe by date interval

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"

Upvotes: 4

Views: 490

Answers (1)

plannapus
plannapus

Reputation: 18749

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"

Upvotes: 3

Related Questions