我有一个有日期列和其他列的dataframe。我需要根据日期进行过滤。
DF
dates A
2018-09 3
2018-10 4
2018-11 2
2018-12 66
2019-01 5在这里,如果criteria_1是2018-10,criteria_2是2018-12,我需要过滤数据,包括这两个条件。
data_ <- data_[grep(criteria_1,data_$dates) & grep(criteria_2,data_$dates)]发布于 2018-12-13 04:43:32
我们可以使用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 66https://stackoverflow.com/questions/53755072
复制相似问题