【问题标题】:How do filter dates in r using dplyr?如何使用 dplyr 过滤 r 中的日期?
【发布时间】:2020-12-13 17:32:51
【问题描述】:

下面是我的数据集:

df_gather %>% 
  filter(Country.Region %in% c("Italy")) %>%
  arrange(desc(Date)) #%>% 
  # filter(Date %in% c(2020-12-12))

########### output #############

Country.Region Date   Cases_Count
<chr>          <date> <int>

Italy   2020-12-12  1825775     
Italy   2020-12-11  1805873     
Italy   2020-12-10  1787147     
Italy   2020-12-09  1770149     
Italy   2020-12-08  1757394     
Italy   2020-12-07  1742557     
Italy   2020-12-06  1728878     
Italy   2020-12-05  1709991     
Italy   2020-12-04  1688939     
Italy   2020-12-03  1664829     

问题:当我尝试使用以下代码filter 时,我得到0 rows 作为回报

df_gather %>% 
  filter(Country.Region %in% c("Italy")) %>%
  arrange(desc(Date)) %>%
  filter(Date %in% c(2020-12-12))

######## output #########
0 rows

也尝试在日期上加上引号,但即便如此我得到相同的结果

df_gather %>% 
  filter(Country.Region %in% c("Italy")) %>%
  arrange(desc(Date)) %>%
  filter(Date %in% c("2020-12-12"))

######## output #########
0 rows

这似乎但无法弄清楚。即使在过滤中也有不同的处理日期的方法吗?

【问题讨论】:

    标签: r dataframe filter


    【解决方案1】:

    应引用日期,最好在相似类型之间进行比较,即转换为 Date 类与 as.Date

    library(dplyr)
    df_gather %>% 
       filter(Country.Region %in% c("Italy")) %>%
       arrange(desc(Date)) %>%
       filter(Date %in% as.Date(c("2020-12-12")))
    

    【讨论】:

    • 我也试过了,但仍然得到 0 行,这也让我感到惊讶
    • @ViSa 你可以尝试用as.Date 包装。更新代码
    • 非常感谢@akrun,因为.Date() 有效。我会尽快接受答案。
    • @ViSa 转换为相同类型总是好的,但字符串应该可以工作。
    • 是的,我同意,但即使我不确定为什么它不能与引号一起使用,那时我认为可能需要在没有引号的情况下使用日期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2018-02-01
    • 2021-11-29
    • 2022-08-18
    • 2018-11-27
    • 2018-11-01
    • 2023-03-21
    相关资源
    最近更新 更多