带负数的日期序列

时间:2011-08-10 02:47:41

标签: r date

如何在给定月份获得结束的每月日期序列且具有给定长度? seq(as.Date(*), length, by="month")假设给出了开始日期,而不是结束日期,而在这种情况下,AFAIK无法为by指定负值。

ETA:也就是说,我想要一个跨越给定时间段的序列,但是要指定一个终点而不是起点。所以,像seq(to="2000-03-01", len=3, by="month") --> 2000-01-01, 2000-02-01, 2000-03-01

4 个答案:

答案 0 :(得分:14)

试试这个:

rev(seq(as.Date("2000-03-01"), length = 3, by = "-1 month"))
## [1] "2000-01-01" "2000-02-01" "2000-03-01"

答案 1 :(得分:5)

library(lubridate)
ymd('2011-03-03') - months(0:5)

答案 2 :(得分:0)

也许您可以使用by=month作为 +1 增量来向前计算,然后反转:

R> rev(seq(as.Date("2011-01-01"), length=6, by="month"))
[1] "2011-06-01" "2011-05-01" "2011-04-01" "2011-03-01" "2011-02-01" "2011-01-01"

答案 3 :(得分:0)

你走了。仅基本功能:

 last.days.of.month <- function(dt) {ldt<- as.POSIXlt(dt)
                                              ldt$mon <- ldt$mon+1
                                              ldt$mday <- 1
                                     return(format( ldt -1, "%Y-%m-%d"))}
 last.days.of.month(as.Date(c("2010-01-06","2010-03-06", "2010-02-06"))  )
# [1] "2010-01-31" "2010-03-31" "2010-02-28"

 seq.ldom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) 
                                    ldt$mon <- ldt$mon+seq(1:nmonths)
                                    ldt$mday <- 1
                        return(format( ldt -1, "%Y-%m-%d"))}
 seq.ldom(as.Date("2010-01-06"), 5)
#[1] "2010-01-31" "2010-02-28" "2010-03-31" "2010-04-30"
#[5] "2010-05-31"

哦,出于某种原因,我以为你想要这个月的最后几天。抱歉无用的代码。这个月的头几天并不难。

seq.fdom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) 
                                        ldt$mon <- ldt$mon+seq(0:(nmonths-1))
                                        ldt$mday <- 1
                            return(format( ldt , "%Y-%m-%d"))}
seq.fdom(as.Date("2010-01-06"), 5)
#[1] "2010-02-01" "2010-03-01" "2010-04-01" "2010-05-01"
#[5] "2010-06-01"

前几个月:

seq.prior.fdom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) 
                                         ldt$mon <- ldt$mon-rev(0:(nmonths-1))
                                         ldt$mday <- 1
                             return(format( ldt , "%Y-%m-%d"))}
      seq.prior.fdom(as.Date("2010-01-06"), 5)
#[1] "2009-09-01" "2009-10-01" "2009-11-01" "2009-12-01"
#[5] "2010-01-01"

我认为基本原则是明确的(如果不是用独木舟划桨打死的话。)