提取在润滑间隔内的月份

时间:2017-10-23 21:29:31

标签: r lubridate

给定一个润滑间隔,例如:

start <- "2016-09-24"
finish <- "2016-11-02"
my_interval <- lubridate::interval(start, finish)
my_interval

> my_interval
[1] 2016-09-24 UTC--2016-11-02 UTC

我希望能够提取落入此区间的月份,在这种情况下:

[1] "Sep" "Oct" "Nov"

到目前为止,我最好的尝试是非常笨重的:

my_months <- list(
  "Aug" = interval("2016-08-01", "2016-08-31"), 
  "Sep" = interval("2016-09-01", "2016-09-30"), 
  "Oct" = interval("2016-10-01", "2016-10-31"), 
  "Nov" = interval("2016-11-01", "2016-11-30"), 
  "Dec" = interval("2016-12-01", "2016-12-31")
)

extract_months <- function(x, months) {
  out <- vector(mode = "character")

  for (i in seq_along(months)) {
    in_month <- int_overlaps(x, months[[i]])
    if (in_month) {
      out[i] <- names(months)[i]
    }
    out <- out[!is.na(out)]
  }
  out
}

extract_months(x = my_interval, months = my_months)

> extract_months(x = my_interval, months = my_months)
[1] "Sep" "Oct" "Nov"
多年来,这很快变得笨拙。我希望有人有更好的解决方案。

我看不出这个问题是如何与Subset a dataframe between 2 dates

重复

2 个答案:

答案 0 :(得分:4)

实际上很简单!

library(lubridate)
month.abb[month(start):month(finish)]

如果这不起作用,请告诉我。

答案 1 :(得分:0)

更进一步的可能包括年份:

library(lubridate)

# the next 12 months starting on the first of next month
my_interval = interval(ceiling_date(Sys.Date(),unit = "month"),
ceiling_date(Sys.Date(),unit = "month") + years(1) - days(1))

year_month_vec <- paste0(year(seq.Date(from = date(int_start(my_interval)),to = date(int_end(my_interval)),by = "month")),"-",
  month.abb[month(seq.Date(from = date(int_start(my_interval)),to = date(int_end(my_interval)),by = "month"))])