R: adding 1 month to a date

后端 未结 2 1789
忘掉有多难
忘掉有多难 2020-12-16 18:09

I want to get the date sequence between a startDate and endDate by adding 1 month to the startDate. ie, if startDate is 2

相关标签:
2条回答
  • 2020-12-16 18:30

    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:

        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"
    
    0 讨论(0)
  • 2020-12-16 18:32

    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.

    0 讨论(0)
提交回复
热议问题