qwww
qwww

Reputation: 1363

Filter a dataframe between two dates

I have a dataframe with dates column and some other column. I need to filter based on dates.

DF

dates   A   
2018-09 3
2018-10 4
2018-11 2
2018-12 66
2019-01 5

here if criteria_1 is 2018-10 and criteria_2 is 2018-12 I need to filter the dataframe including those two criteria.

data_ <- data_[grep(criteria_1,data_$dates) & grep(criteria_2,data_$dates)]

Upvotes: 0

Views: 136

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

We can use grep to get row indices and then subset the dataframe.

criteria_1 = "2018-10"
criteria_2 = "2018-12"
df[grep(criteria_1, df$dates):grep(criteria_2, df$dates), ]

#   dates  A
#2 2018-10  4
#3 2018-11  2
#4 2018-12 66

If there are some out-of-range issues we can use match instead with proper nomatch arguments

df[match(criteria_1, df$dates, nomatch = 1):
   match(criteria_2, df$dates, nomatch = nrow(df)), ]

So if crietria_2 is out-of-range by default it goes to last row

criteria_1 = "2018-10"
criteria_2 = "2018-aa"
df[match(criteria_1, df$dates, nomatch = 1):
   match(criteria_2, df$dates, nomatch = nrow(df)), ]

#    dates  A
#2 2018-10  4
#3 2018-11  2
#4 2018-12 66
#5 2019-01  5

and if criteria_1 is out-of-range we can go to first row by default it does to first row

criteria_1 = "2018-aa"
criteria_2 = "2018-12"
df[match(criteria_1, df$dates, nomatch = 1):
   match(criteria_2, df$dates, nomatch = nrow(df)), ]

#    dates  A
#1 2018-09  3
#2 2018-10  4
#3 2018-11  2
#4 2018-12 66

Upvotes: 1

Related Questions