Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: adding 1 month to a date

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

like image 267
Dinoop Nair Avatar asked Jul 16 '13 15:07

Dinoop Nair


People also ask

What is Lubridate R?

Lubridate is an R package that makes it easier to work with dates and times. Below is a concise tour of some of the things lubridate can do for you. Lubridate was created by Garrett Grolemund and Hadley Wickham, and is now maintained by Vitalie Spinu.

How do you set a variable in R date?

To create a Date object from a simple character string in R, you can use the as. Date() function. The character string has to obey a format that can be defined using a set of symbols (the examples correspond to 13 January, 1982): %Y : 4-digit year (1982)

How do I format a date column in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


2 Answers

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

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

like image 171
ialm Avatar answered Oct 18 '22 11:10

ialm


This is not working, because R is not sure what to do with last day of the month. So I have a simple solution: do the same but use 1st day of the next month and then substract 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"
like image 30
bartektartanus Avatar answered Oct 18 '22 09:10

bartektartanus