在 R 中获取最近 6 个月的数据

Getting the last 6 months data in R

我有一个包含很多行的数据框。这是:

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)

我只想对 game_data 进行子集化以获取最近 6 个月的所有数据。我如何获得它?

数据中自 max 日期起的最近 6 个月的数据?

你可以试试-

library(lubridate)
library(dplyr)

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

或者用 dplyr -

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