Problems adding a month to X using POSIXlt in R - need to reset value using as.Date(X)

前端 未结 3 776
不知归路
不知归路 2020-12-22 05:14

This works for me in R:

# Setting up the first inner while-loop controller, the start of the next water year
  NextH2OYear <- as.POSIXlt(firstDate)
  Next         


        
相关标签:
3条回答
  • 2020-12-22 05:45

    Here is you can add 1 month to a date in R, using package lubridate:

    library(lubridate)
    x <- as.POSIXlt("2010-01-31 01:00:00")
    month(x) <- month(x) + 1
    
    >x
    [1] "2010-03-03 01:00:00 PST"
    

    (note that it processed the addition correctly, as 31st of Feb doesn't exist).

    0 讨论(0)
  • 2020-12-22 05:51

    Plain R

    seq(Sys.Date(), length = 2, by = "month")[2]
    seq(Sys.Date(), length = 2, by = "year")[2]
    

    Note that this works with POSIXlt too, e.g.

    seq(as.POSIXlt(Sys.Date()), length = 2, by = "month")[2]
    

    mondate.

    library(mondate)
    now <- mondate(Sys.Date())
    now + 1  # date in one month
    now + 12  # date in 12 months
    

    Mondate is bit smarter about things like mondate("2013-01-31")+ 1 which gives last day of February whereas seq(as.Date("2013-01-31"), length = 2, by = "month")[2] gives March 3rd.

    yearmon If you don't really need the day part then yearmon may be preferable:

    library(zoo)
    now.ym <- yearmon(Sys.Date())
    now.ym + 1/12 # add one month
    now.ym + 1 # add one year
    

    ADDED comment on POSIXlt and section on yearmon.

    0 讨论(0)
  • 2020-12-22 06:01

    Can you perhaps provide a reproducible example? What's in firstDate, and what version of R are you using? I do this kind of manipulation of POSIXlt dates quite often and it seems to work:

    Sys.Date()
    # [1] "2013-02-13"
    date = as.POSIXlt(Sys.Date())
    date$mon = date$mon + 1
    as.Date(date)
    # [1] "2013-03-13"
    
    0 讨论(0)
提交回复
热议问题