81

R 中是否有一种简单的方法可以逐项列出两个指定日期之间发生的所有有效日期?例如,我想要以下输入:

itemizeDates(startDate="12-30-11", endDate="1-4-12")

生成以下日期:

"12-30-11" "12-31-11", "1-1-12", "1-2-12", "1-3-12", "1-4-12"

我对日期的课程和格式很灵活,我只需要一个概念的实现。

4

3 回答 3

141

您正在寻找seq

> seq(as.Date("2011-12-30"), as.Date("2012-01-04"), by="days")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"

或者,您可以使用:

> as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"), origin="1970-01-01")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"

这是满足您特定要求的功能

itemizeDates <- function(startDate="12-30-11", endDate="1-4-12", 
                         format="%m-%d-%y") {
  out <- seq(as.Date(startDate, format=format), 
             as.Date(endDate, format=format), by="days")  
  format(out, format)
}

> itemizeDates(startDate="12-30-11", endDate="1-4-12")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"
于 2013-01-22T02:02:56.017 回答
16

我更喜欢使用 lubridate 包来解决日期时间问题。一旦你知道它就更直观,更容易理解和使用。

library(lubridate)
#mdy() in lubridate package means "month-day-year", which is used to convert
#the string to date object
>start_date <- mdy("12-30-11")
>end_date <- mdy("1-4-12")
#calculate how many days in this time interval
>n_days <- interval(start_date,end_date)/days(1)
>start_date + days(0:n_days)
[1]"2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04"
#convert to original format
format(start_date + days(0:n_days), format="%m-%d-%y")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"

参考: 使用 lubridate 轻松实现日期和时间

于 2018-02-03T22:28:45.157 回答
8

2个类似的实现lubridate

library(lubridate)

as_date(mdy("12-30-11"):mdy("1-4-12"))

# OR

seq(mdy("12-30-11"), mdy("1-4-12"), by = "days")

这些不会将您的日期格式化为月-日-年,但您可以根据需要修复格式。但是在分析时,年-月-日有点容易处理。

于 2020-09-18T17:22:47.657 回答