简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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