Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create end of the month date from a date variable

Tags:

date

dataframe

r

I have a large data frame with date variables, which reflect first day of the month. Is there an easy way to create a new data frame date variable that represents the last day of the month?

Below is some sample data:

date.start.month=seq(as.Date("2012-01-01"),length=4,by="months") df=data.frame(date.start.month) df$date.start.month  "2012-01-01" "2012-02-01" "2012-03-01" "2012-04-01" 

I would like to return a new variable with:

"2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30" 

I've tried the following but it was unsuccessful:

df$date.end.month=seq(df$date.start.month,length=1,by="+1 months") 
like image 626
MikeTP Avatar asked Feb 29 '12 17:02

MikeTP


People also ask

How can I get end of month in PHP?

$date = strtotime ( $datestring ); // Last date of current month. $day = date ( "l" , $lastdate );

How do I add months to a date in SPSS?

To add months to a date value, you will wish to use the DATESUM function in SPSS. For example, if I want to add two months to a date variable, I may use the following syntax: COMPUTE datevar2=datesum(datevar,2,"MONTHS"). EXECUTE.


1 Answers

To get the end of months you could just create a Date vector containing the 1st of all the subsequent months and subtract 1 day.

date.end.month <- seq(as.Date("2012-02-01"),length=4,by="months")-1 date.end.month [1] "2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30" 
like image 135
James Avatar answered Sep 17 '22 15:09

James