获取r中最近6个月的数据



我有一个包含很多行的数据帧。

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))

最新更新