简体   繁体   English

基于日期比较R的子集数据集

[英]subset dataset based on date comparison R

I have a dataset as shown below 我有一个数据集,如下所示

    Col1      Col2       Col3        CutoffDate
    12001     Yes        2008-08-15  2008-08-10
    12001     Yes        2008-08-22  2008-08-10
    12001     Yes        2008-08-10  2008-08-10
    12001     Yes        2008-08-04  2008-08-10

I am only interested in retaining the last two rows because they are less than or equal to the Cutoff Date 2008-08-10 . 我只想保留最后两行,因为它们小于或等于截止日期2008-08-10

The final dataset should look like this 最终数据集应如下所示

    Col1      Col2       Col3        CutoffDate
    12001     Yes        2008-08-10  2008-08-10
    12001     Yes        2008-08-04  2008-08-10

I know the subset function in R but not sure how to do this , any help is much appreciated. 我知道R中的子集函数,但不确定如何执行此操作,非常感谢您的帮助。

You can just use regular comparison 您可以使用常规比较

dat[dat$Col3 <= dat$CutoffDate, ]
#    Col1 Col2       Col3 CutoffDate
# 3 12001  Yes 2008-08-10 2008-08-10
# 4 12001  Yes 2008-08-04 2008-08-10

Assuming Col3 and CuttoffDate are class "Date" 假设Col3和CuttoffDate是“ Date”类

or maybe preferably, 或最好是

with(dat, dat[Col3 <= CutoffDate, ])

You can use subset() : 您可以使用subset()

df <- data.frame(Col1=c(12001,12001,12001,12001),Col2=c('Yes','Yes','Yes','Yes'),Col3=as.Date(c('2008-08-15','2008-08-22','2008-08-10','2008-08-04')),CutoffDate=as.Date(c('2008-08-10','2008-08-10','2008-08-10','2008-08-10')));
subset(df,Col3<=CutoffDate);
##    Col1 Col2       Col3 CutoffDate
## 3 12001  Yes 2008-08-10 2008-08-10
## 4 12001  Yes 2008-08-04 2008-08-10

And if you are using dplyr: 如果您使用的是dplyr:

library(dplyr)
df <- data.frame(Col1 = c(12001, 12001, 12001, 12001),
                 Col2 = c("Yes", "Yes", "Yes", "Yes"),
                 Col3 = as.Date(c("2008-08-15", "2008-08-22", "2008-08-10", "2008-08-04")),
                 CutoffDate = as.Date(c("2008-08-10", "2008-08-10", "2008-08-10", "2008-08-10")))

df %>% filter(Col3 <= CutoffDate)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM