创建两个日期之间全天的向量 [英] Create a Vector of All Days Between Two Dates
本文介绍了创建两个日期之间全天的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
R中是否有一种简便的方法可以逐项列出在两个指定日期之间发生的所有有效日期?例如,我想要以下输入:
Is there an easy way in R for me to itemize all valid days that occurred between two specified dates? For instance, I'd like the following inputs:
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"
我对日期的类和格式很灵活,我只需要实现这个概念即可.
I'm flexible on classes and formatting of the dates, I just need an implementation of the concept.
推荐答案
您正在寻找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"
此功能可以满足您的特定要求
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"
这篇关于创建两个日期之间全天的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文