根据两个日期创建月份和年份向量

时间:2018-09-25 14:27:27

标签: r date

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

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 个答案:

答案 0 :(得分:2)

尝试:

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

答案 1 :(得分:0)

使用lubridate

library(lubridate)

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

或在基数R中使用format

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

答案 2 :(得分:0)

按月创建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(.)) }