R:添加1个月的日期 [英] R: adding 1 month to a date

查看:979
本文介绍了R:添加1个月的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在<$ c中添加1个月来获取 startDate endDate 之间的日期顺序$ c> startDate 。即,如果 startDate 是2013-01-31和 endDate 是2013-07-31,我宁愿看到日期如下:

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:


2013-01-312013-02-282013-03-312013- 04-302013-05-312013-06-302013-07-31

"2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"

我有尝试 seq.Date(as.Date(2013-01-31),by =month,length.out = 7)
但是这个代码的输出是这样的。

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)
[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?

推荐答案

p>我必须在R中使用日期,我发现日期数据中最有用的一个包是 lubridate 。对于您的问题,您可以简单地执行以下操作:

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:

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

code>还有很多其他功能的日期,我强烈推荐看看。

lubridate also has many other functions for dates, and I highly recommend taking a look.

这篇关于R:添加1个月的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆