How to call the previous month in R?

4

I need R to tell me the month before we are, that is, we are in "2018-05" and I need him to give me "2018-04". So far my solution was:

format(Sys.Date()-as.integer(format(Sys.Date(), "%d")),"%Y-%m")

I believe there should be a more "clean" solution.

    
asked by anonymous 11.06.2018 / 21:23

2 answers

3

You can also use mondate :

library(mondate)

mondate(Sys.Date())-1
# mondate: timeunits="months"
# [1] 05/12/2018

And to format only year and month:

format(mondate(Sys.Date())-1, "%Y-%m")
# [1] "2018-05"
    
12.06.2018 / 01:50
3

With lubridate , you can do this:

library(lubridate)
month(today() - months(1))
    
11.06.2018 / 22:02