Negative value data sequence

How do I get a sequence of monthly dates that ends in a given month and has a given length? seq(as.Date(*), length, by="month") assumes that the start date is given, not the end date, and AFAIK it is not possible to specify a negative value for by in this case.

ETA: that is, I want a sequence that spans a specific period, but one whose endpoint is indicated, not the starting point. So, something like seq(to="2000-03-01", len=3, by="month") --> 2000-01-01, 2000-02-01, 2000-03-01 .

+6
source share
4 answers

Try the following:

 rev(seq(as.Date("2000-03-01"), length = 3, by = "-1 month")) ## [1] "2000-01-01" "2000-02-01" "2000-03-01" 
+11
source
 library(lubridate) ymd('2011-03-03') - months(0:5) 
+5
source

Perhaps you could just figure it out ahead using by=month as an increment of +1, and then change:

 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" 
0
source

Here you go. Basic functions only:

  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" 

Oh, for some reason I thought you needed the last days of the month. Sorry for the useless code. The first days of the month are not difficult.

 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" 

And get the previous months:

 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" 

I think the basic principle is clear (unless you beat the oars with a canoe to death.)

0
source

Source: https://habr.com/ru/post/894690/


All Articles