Search code examples
rfilterdplyrmutated

Filtering on a date using dplyr without changing the variable format


I want use a list of years to filter a database by date

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)

The above code works and lets me filter my dataset but it also formats the date column. Is there a way to get my filter results without having the format of the date column change in the finished subset dataframe?


Solution

  • If you're up for using the lubridate package you could do:

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

    Which gives:

    #   animal     mydate
    # 1    pig 2014-01-01