【问题标题】:Filtering dates in dplyr在 dplyr 中过滤日期
【发布时间】:2016-03-17 22:11:38
【问题描述】:

我的 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

结果应该是:

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

我尝试了以下但它返回空的空向量。

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 月份的数据。

有没有更有效的方法,比如在 dplyr 上使用 between 运算符对 Date 类型变量?

【问题讨论】:

  • 您能否在问题中添加 str(p2p_dt_SKILL_A)。我想看看 Date 是 date 对象还是别的东西
  • @PLapointe 它已经在返回部分。 Variables not shown: Patch (fctr), Date (date), Prod_DL (dbl) ...它是一个日期类型
  • 代码的那部分中没有引用日期 (")。使用上面的代码,它可以工作。看看下面我的答案。
  • @PLapointe 尝试使用引号和取消引号...不起作用...我的数据框类型为 tbl_df
  • 这能回答你的问题吗? Subset a dataframe between 2 dates

标签: r date filter dplyr between


【解决方案1】:

如果日期格式正确为date,则您的第一次尝试有效:

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

【讨论】:

    【解决方案2】:

    另一个更详细的选项是使用函数betweenx >= left & x 的快捷方式。我们需要更改日期以考虑= 符号,并使用as.Date(解释here)。

    p2p_dt_SKILL_A%>%
                    select(Patch,Date,Prod_DL)%>%
                    filter(between(Date, as.Date("2015-09-05"),as.Date("2015-09-17")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多