Search code examples
rdplyrtidyrplyr

Getting the last 6 months data in R


i had data frame which contain many row. Here it is:

library(lubridate)

date_ <- date(seq(ymd_h("2020-01-01-00"), ymd_h("2021-03-31-23"), by = "hours"))
hour_ <- hour(seq(ymd_h("2020-01-01-00"), ymd_h("2021-03-31-23"), by = "hours"))

game1 <- sort(round(runif(length(date_), 10, 50), 0), decreasing = TRUE)
game2 <- sort(round(runif(length(date_), 20, 100), 0), decreasing = TRUE)
game3 <- sort(round(runif(length(date_), 30, 150), 0), decreasing = TRUE)
game4 <- sort(round(runif(length(date_), 40, 200), 0), decreasing = TRUE)

game_data <- data.frame(date_, hour_, game1, game2, game3, game4)

I just want to subset game_data to get all the last 6 months data. How do i get it?


Solution

  • Last 6 months of data from the max date in the data ?

    You can try -

    library(lubridate)
    library(dplyr)
    
    result <- subset(game_data, date_ > max(date_) %m-% months(6))
    

    Or with dplyr -

    result <- game_data %>% filter(date_ > max(date_) %m-% months(6))