Filtering dates in dplyr

前端 未结 2 595
[愿得一人]
[愿得一人] 2021-02-05 03:31

My tbl_df:

    > p2p_dt_SKILL_A%>%
    + select(Patch,Date,Prod_DL)%>%
    + head()
      Patch       Date Prod_DL
    1  P1 2015-09-04    3.43
    2 P11         


        
相关标签:
2条回答
  • 2021-02-05 04:11

    If Date is properly formatted as a date, your first try works:

    p2p_dt_SKILL_A <-read.table(text="Patch,Date,Prod_DL
    P1,9/4/2015,3.43
    P11,9/11/2015,3.49
    P12,9/18/2015,3.45
    P13,12/6/2015,3.57
    P14,12/13/2015,3.43
    P15,12/20/2015,3.47
    ",sep=",",stringsAsFactors =FALSE, header=TRUE)
    
    p2p_dt_SKILL_A$Date <-as.Date(p2p_dt_SKILL_A$Date,"%m/%d/%Y")
    
    p2p_dt_SKILL_A%>%
                    select(Patch,Date,Prod_DL)%>%
                    filter(Date > "2015-09-04" & Date <"2015-09-18")
      Patch       Date Prod_DL
    1 P11 2015-09-11    3.49
    


    Still works if data is of type tbl_df.

    p2p_dt_SKILL_A <-tbl_df(p2p_dt_SKILL_A)
    
    p2p_dt_SKILL_A%>%
                    select(Patch,Date,Prod_DL)%>%
                    filter(Date > "2015-09-04" & Date <"2015-09-18")
    Source: local data frame [1 x 3]
    
      Patch       Date Prod_DL
      (chr)     (date)   (dbl)
    1 P11 2015-09-11    3.49
    
    0 讨论(0)
  • 2021-02-05 04:11

    Another more verbose option would be to use the function between, a shortcut for x >= left & x <= right. We need to change the days to account for the = sign, and to use as.Date (explanation here).

    p2p_dt_SKILL_A%>%
                    select(Patch,Date,Prod_DL)%>%
                    filter(between(Date, as.Date("2015-09-05"),as.Date("2015-09-17")))
    
    0 讨论(0)
提交回复
热议问题