在日期向量中的每个日期添加一天

时间:2016-04-23 21:04:58

标签: r date

我有一个名为KeyDates的日期向量,其中包含两个关键日期。我想按时间顺序制作一个名为KeyDatesPlus的新日期向量,其中包含这两个关键日期和两天之后的日期。

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"

我怎么能实现这一目标?非常感谢你。

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

或者:

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用软件包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区分“时期”与“持续时间”。

  • 时间段是时钟上的时间(即,如果发生夏令时,则是时钟读取的内容)。这就是使用days()在此处指定的内容。
  • 持续时间是物理时间(例如,如果发生夏令时,则是您实际坐在那里的时间。)可以使用ddays()来指定。