代码之家  ›  专栏  ›  技术社区  ›  jakes

基于两个日期创建月和年向量

  •  0
  • jakes  · 技术社区  · 6 年前

    我有开始日期和结束日期,如下所示:

    date1 <- '01-03-2011'
    date2 <- '30-09-2013'
    

    months <- c(3:12, 1:12, 1:9)
    years <- c(rep(2011, 10), rep(2012, 12), rep(2013, 9))
    

    最快的方法是什么?

    3 回复  |  直到 6 年前
        1
  •  2
  •   nghauran    6 年前

    尝试:

    date1 <- "01-03-2011"
    date2 <- "30-09-2013"
    dates <- seq(as.Date(date1, "%d-%m-%Y"), as.Date(date2, "%d-%m-%Y"), by = "month")
    as.numeric(substring(dates, 6, 7)) # months
    # [1]  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9
    as.numeric(substring(dates, 1, 4)) # years
    # [1] 2011 2011 2011 2011 2011 2011 2011 2011 2011 2011 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2013
    #[24] 2013 2013 2013 2013 2013 2013 2013 2013
    
        2
  •  0
  •   acylam    6 年前

    lubridate

    library(lubridate)
    
    dates <- seq(dmy(date1), dmy(date2), by = 'month')
    months <- month(dates)
    years <- year(dates)
    

    或与 format 底部R:

    months <- as.numeric(format(dates, "%m"))
    years <- as.numeric(format(dates, "%Y"))
    

    输出:

    > months
     [1]  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5
    [28]  6  7  8  9
    > years
     [1] 2011 2011 2011 2011 2011 2011 2011 2011 2011 2011 2012 2012 2012 2012 2012 2012
    [17] 2012 2012 2012 2012 2012 2012 2013 2013 2013 2013 2013 2013 2013 2013 2013
    
        3
  •  0
  •   G. Grothendieck    6 年前

    按月份创建yearmon向量,然后选择年份和月份:

    library(zoo)
    
    fmt <- "%d-%m-%Y"
    ym <- seq(as.yearmon(date1, fmt), as.yearmon(date2, fmt), by = 1/12)
    years <- as.integer(ym)
    months <- cycle(ym)
    

    library(magrittr)
    library(zoo)
    
    fmt <- "%d-%m-%Y"
    data.frame(date1, date2) %$%
      seq(as.yearmon(date1, fmt), as.yearmon(date2, fmt), by = 1/12) %>% 
      { data.frame(year = as.integer(.), month = cycle(.)) }