Krug
Krug

Reputation: 1013

Add one day to every date in a days vector

I have a vector of dates called KeyDates containing two key dates. I would like to make a new vector of dates called KeyDatesPlus containing those two key dates and the two days after, in chronological order.

KeyDates <- structure(c(15159,15165), class = "Date")

#KeyDates Output:
[1] "2011-07-04" "2011-07-10"

#desired output for KeyDatesPlus:
[1] "2011-07-04" "2011-07-05" "2011-07-10" "2011-07-11"

How could I achieve that? Thank you very much.

Upvotes: 0

Views: 90

Answers (5)

rrr
rrr

Reputation: 2008

An answer using the package lubridate:

library("lubridate")
your.vector <- c("2011-07-04", "2011-07-10")
your.vector <- parse_date_time(x = your.vector, orders = "ymd")
your.vector
# [1] "2011-07-04 UTC" "2011-07-10 UTC"

one.day <- days(x = 1)
one.day
# [1] "1d 0H 0M 0S"
your.vector + one.day
# [1] "2011-07-05 UTC" "2011-07-11 UTC"

# your exact desired output (non-UTC time zone can be specified in parse_date_time):
new.vector <- sort(x = c(your.vector, your.vector + one.day))
# [1] "2011-07-04 UTC" "2011-07-05 UTC" "2011-07-10 UTC" "2011-07-11 UTC"

Lubridate distinguishes a "period" from a "duration."

  • A period is the time on the clock (ie if daylight savings time happens, it's what the clock reads). That's what's specified here using days().
  • A duration is the physical time (ie if daylight savings time happens, it's how long you've actually been sitting there.) That could be specified instead using ddays().

Upvotes: 1

Bryce F
Bryce F

Reputation: 101

KeyDates <- structure(c(15159,15165), class = "Date")
KeyDates.plus <- as.Date(sapply(KeyDates, function(x) c(x, x+1)))

Upvotes: 1

IRTFM
IRTFM

Reputation: 263481

structure( sapply(KeyDates, "+", (0:1)), class = "Date")
[1] "2011-07-04" "2011-07-05" "2011-07-10" "2011-07-11"

Or:

 as.Date( sapply(KeyDates, "+", (0:1)))
[1] "2011-07-04" "2011-07-05" "2011-07-10" "2011-07-11"

Upvotes: 1

dww
dww

Reputation: 31454

KeyDates <- structure(c(15159,15165), class = "Date")
KeyDatesPlus <- KeyDates+1
KeyDatesPlus <- sort(unique(c(KeyDates, KeyDatesPlus)))

Upvotes: 0

Richard Telford
Richard Telford

Reputation: 9923

sort(c(KeyDates, KeyDates + 1))
[1] "2011-07-04" "2011-07-05" "2011-07-10" "2011-07-11"

Upvotes: 1

Related Questions