使用 dplyr 在不更改变量格式的情况下过滤日期

Filtering on a date using dplyr without changing the variable format

我想使用年份列表按日期过滤数据库

years<-c("2014")
yearsdata <- data.frame(animal=c("cow","pig"),
                        mydate=c(as.Date("2015-01-01"),
                        as.Date("2014-01-01")))
yearsdata %>% 
          mutate(mydate =format(mydate, "%Y") %>% 
          as.character()) %>%     
          filter(is.null(years) | mydate %in% years)

上面的代码有效,让我可以过滤我的数据集,但它也格式化了日期列。有没有办法在不更改已完成子集数据框中日期列格式的情况下获取我的过滤结果?

这些管子让我很头疼,我会做的

library(data.table)
setDT(yearsdata)[is.null(years) | year(mydate) %in% years]
#    animal     mydate
# 1:    pig 2014-01-01

如果您准备使用 lubridate 软件包,您可以这样做:

library("lubridate")

yearsdata %>%
  filter(is.null(years) | year(mydate) %in% years)

给出:

#   animal     mydate
# 1    pig 2014-01-01