linus heinz
linus heinz

Reputation: 459

Adding half a month with lubridate

I want to add multiple steps of halfe a month with lubridate

for (i in range) {
  if(i%%2==1){
    day(dateseq[i]) <-  day(15)
  }
  if (i%%2==0) {
    dateseq[i] <- ceiling_date(dateseq[i-1], unit='month')
  }
}

but i think there should be a more efficent way to do that

Edit: the basic technique should work like this

dateseq <- as_datetime(rep.int(ymd_hms("2016-11-01_3-50-23"),15))
range <- 1:15
for (i in range) {
  if(i%%2==1){
    day(dateseq[i]) <-  15
  }
  if (i%%2==0) {
    dateseq[i] <- ceiling_date(dateseq[i-1])
  }
}

So it jumps between the 15 and the 1 of the following month Edit : preventing R error

Upvotes: 1

Views: 191

Answers (1)

Martin
Martin

Reputation: 1201

This would be my solution without a loop:

library(lubridate)

dateseq <- seq(from = ymd_hms("2016-11-01_3-50-23"),
               length.out = 15, by = "months")

day(dateseq) <- rep(c(1,15), length(dateseq)/2+1)[1:length(dateseq)]

dateseq

This gives alternating one month starting 1st, the next the 15th.

Based on your comment I'm not sure if what you need is each month once starting 1st and once the 15th. In this case this should work:

dateseq <- sort(rep(seq(from = ymd_hms("2016-11-01_3-50-23"),
                        length.out = 15, by = "months"),
                    2))

day(dateseq) <- rep(c(1,15), length(dateseq)/2+1)[1:length(dateseq)]

dateseq

Upvotes: 1

Related Questions