subset dataset based on date comparison R

后端 未结 3 378
野趣味
野趣味 2021-01-23 03:51

I have a dataset as shown below

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


        
相关标签:
3条回答
  • 2021-01-23 04:11

    And if you are using 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)
    
    0 讨论(0)
  • 2021-01-23 04:25

    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"

    or maybe preferably,

    with(dat, dat[Col3 <= CutoffDate, ])
    
    0 讨论(0)
  • 2021-01-23 04:29

    You can use 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
    
    0 讨论(0)
提交回复
热议问题