创建两个日期之间所有天数的矢量

是否有一个简单的方法,我在 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"

我对类和日期格式的灵活性,我只是需要一个概念的实现。

76094 次浏览

You're looking for 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"

Or, you can use :

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

Note that with : "Non-numeric arguments are coerced internally". Thus, we convert back to class Date, using as.Date method for class 'numeric' and provide origin.


Here's a function to meet your specific request

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"

I prefer using the lubridate package to solve datetime problems. It is more intuitive and easier to understand and use once you know it.

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"

Reference: Dates and Times Made Easy with lubridate

2 similar implementations in 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")

These don't format your dates in month-day-year but you can fix the formatting if you want. But year-month-day is a bit easy to work with when analyzing.