简体   繁体   English

如何使用 dplyr 过滤 r 中的日期?

[英]How do filter dates in r using dplyr?

Below is my dataset:下面是我的数据集:

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     

Issue: when I try to filter this using below code I get 0 rows in return问题:当我尝试使用下面的代码filter它时,我得到0 rows作为回报

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

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

Also tried with quotes on dates but even then I get same result还尝试在日期上加上引号,但即使那样我也得到相同的结果

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

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

This seems but not able to figure out.这似乎但无法弄清楚。 Is there a different method of handling dates even in filtering?即使在过滤中也有不同的处理日期的方法吗?

The date should be quoted and it is better to compare across similar types ie convert to Date class with as.Date应引用日期,最好在类似类型之间进行比较,即使用 as.Date 转换为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")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM