在 dplyr 中过滤日期 [英] Filtering dates in dplyr

查看:17
本文介绍了在 dplyr 中过滤日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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 2015-09-11    3.49
    3 P12 2015-09-18    3.45
...
    4 P13 2015-12-06    3.57
    5 P14 2015-12-13    3.43
    6 P15 2015-12-20    3.47

我想根据日期选择所有 rows 例如,如果 Date 大于 2015-09-04 并且小于 <代码>2015-09-18

I want to select all rows based on the date for example if Date is greater than 2015-09-04 and less than 2015-09-18

结果应该是:

      Patch       Date          Prod_DL
      P1        2015-09-04    3.43
      P11       2015-09-11    3.49

我尝试了以下操作,但它返回空的空向量.

I tried the following but it returns empty empty vector.

p2p_dt_SKILL_A%>%
                select(Patch,Date,Prod_DL)%>%
                filter(Date > "2015-09-04" & Date <"2015-09-18")

刚回来:

> p2p_dt_SKILL_A%>%
+                 select(Patch,Date,Prod_DL)%>%
+                 filter(Date > 2015-09-12 & Date <2015-09-18)
Source: local data table [0 x 3]

Variables not shown: Patch (fctr), Date (date), Prod_DL (dbl)

也试过用引号.

并使用lubridate

p2p_dt_SKILL_A%>%
                select(Patch,Date,Prod_DL)%>%
                #filter(Date > 2015-09-12 & Date <2015-09-18)%>%
                filter(Patch %in% c("BVG1"),month(p2p_dt_SKILL_A$Date) == 9)%>%
                arrange(Date)

但这给了我整个 9 月的数据.

But this gives me whole September data.

是否有更有效的方法,例如在 Date 类型变量上使用 dplyr 中的 between 运算符?

Is there a more efficient way like using the between operator from dplyr on Date types variables?

推荐答案

如果 Date 正确格式化为 date,您的第一次尝试有效:

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



如果数据是 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

这篇关于在 dplyr 中过滤日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆