I want to get the date sequence between a startDate
and endDate
by adding 1 month to the startDate
. ie, if startDate
is 2013-01-31 and endDate
is 2013-07-31, I would prefer to see dates like this:
我想通过在startDate中添加1个月来获取startDate和endDate之间的日期序列。即,如果startDate是2013-01-31而endDate是2013-07-31,我希望看到这样的日期:
"2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"
“2013-01-31”“2013-02-28”“2013-03-31”“2013-04-30”“2013-05-31”“2013-06-30”“2013-07-31”
I have tried seq.Date(as.Date("2013-01-31"),by="month",length.out=7)
. But the output of this code is like this
我试过seq.Date(as.Date(“2013-01-31”),by =“month”,length.out = 7)。但是这段代码的输出是这样的
> seq.Date(as.Date("2013-01-31"),by="month",length.out=7)
[1] "2013-01-31" "2013-03-03" "2013-03-31" "2013-05-01" "2013-05-31" "2013-07-01" "2013-07-31"
So,what is the simplest solution to get the correct output?
那么,获得正确输出的最简单的解决方案是什么?
2 个解决方案
#1
17
I have to work with dates in R, and one of the most useful packages that I found for date data is lubridate
. For your problem, you can simply do the following:
我必须使用R中的日期,我在日期数据中找到的最有用的包之一是lubridate。对于您的问题,您可以简单地执行以下操作:
require(lubridate)
# ymd function parses dates in year-month-day format
startDate <- ymd('2013-01-31')
# The %m+% adds months to dates without exceeding the last day
myDates <- startDate %m+% months(c(0:6))
lubridate
also has many other functions for dates, and I highly recommend taking a look.
lubridate还有许多其他日期功能,我强烈建议你看看。
#2
14
This is not working, because R is not sure what to do with last day of the month :) So I have simple solution. Do the same but use 1st day of the next month and then substract 1:
这是行不通的,因为R不知道该怎么处理这个月的最后一天:)所以我有简单的解决方案。做同样的但是使用下个月的第一天然后减去1:
seq(as.Date("2013-02-1"),by="month",length.out=7)-1
[1] "2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"
#1
17
I have to work with dates in R, and one of the most useful packages that I found for date data is lubridate
. For your problem, you can simply do the following:
我必须使用R中的日期,我在日期数据中找到的最有用的包之一是lubridate。对于您的问题,您可以简单地执行以下操作:
require(lubridate)
# ymd function parses dates in year-month-day format
startDate <- ymd('2013-01-31')
# The %m+% adds months to dates without exceeding the last day
myDates <- startDate %m+% months(c(0:6))
lubridate
also has many other functions for dates, and I highly recommend taking a look.
lubridate还有许多其他日期功能,我强烈建议你看看。
#2
14
This is not working, because R is not sure what to do with last day of the month :) So I have simple solution. Do the same but use 1st day of the next month and then substract 1:
这是行不通的,因为R不知道该怎么处理这个月的最后一天:)所以我有简单的解决方案。做同样的但是使用下个月的第一天然后减去1:
seq(as.Date("2013-02-1"),by="month",length.out=7)-1
[1] "2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"