Home > Software engineering >  How to filter data based on year in R
How to filter data based on year in R

Time:03-01

i was wondring how i could filter this data based on years, for instance 2018 or 2019 alone?

Thank you

enter image description here

enter image description here

CodePudding user response:

Example filter for 2018.

date <- c("2015-01-01",
          "2018-01-01", "2018-05-01", "2018-06-01" ,"2018-08-01",
          "2019-01-01", "2019-05-01", "2019-06-01" ,"2019-08-01",
          "2020-01-01", "2020-05-01", "2020-06-01" ,"2020-08-01")
temp <- data.frame(date)

temp$date <- as.Date(temp$date, format= "%Y-%m-%d")

subdate <- subset(temp, date> "2018-01-01" & date < "2019-01-01")

print(subdate)
        date
3 2018-05-01
4 2018-06-01
5 2018-08-01

CodePudding user response:

Using lubridate to filter the year of the date:

df <- tibble::tibble(price = runif(10)*100, 
               listingPrice = price*runif(1), 
               date = c("2015-01-01", "2018-01-01", "2018-05-01", "2018-06-01" ,"2018-08-01", "2019-01-01", 
                        "2019-05-01", "2019-06-01" ,"2019-08-01", "2020-01-01"))
    
df |>
  dplyr::filter(lubridate::year(date) %in% c(2018, 2019))
  • Related