筛选两个日期之间的数据框

时间:2018-12-13 04:36:12

标签: r dataframe

我有一个带有日期列和其他列的数据框。我需要根据日期进行过滤。

DF

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

在这里,如果criteria_12018-10并且criteria_22018-12,则需要过滤包含这两个条件的数据框。

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

1 个答案:

答案 0 :(得分:1)

我们可以使用grep获取行索引,然后对数据帧进行子集化。

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

如果存在一些超出范围的问题,我们可以使用match来代替适当的nomatch参数

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

因此,如果crietria_2超出范围default,它将转到最后一行

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

如果criteria_1超出范围,我们可以按default转到第一行

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
相关问题