0

I want to subtract months from given date in year and month format.

global_date = "2017-01"

I am converting it with the zoo library as follows:

as.yearmon(global_date) - 0.1

but it gives me Nov 2016, I want it as '201612'

How can I do it in R?

Henrik
  • 65,555
  • 14
  • 143
  • 159
Neil
  • 7,937
  • 22
  • 87
  • 145
  • 4
    There are already answers but I would like to point out that the answer could have been found in the docs. Please see `?as.yearmon`: _The "yearmon" class is used to represent monthly data. Internally it holds the data as year plus 0 for January, 1/12 for February, 2/12 for March and so on [...]_ This tells to subtract `1/12` instead of `0.1` to go to the previous month. – Uwe Jan 02 '17 at 11:33

2 Answers2

7

As we want to subtract one month, we should subtract 1/12 which is 0.083 and not 0.1

library(zoo)
as.yearmon(global_date) - (1/12)
#[1] "Dec 2016"

If we need output in the mentioned format

format(as.yearmon(global_date) - (1/12), "%Y%m")
#[1] "201612"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Using only base R and making only minimal changes to the OP's code

format(as.Date(paste0(global_date, "-01")) - 0.1*10, "%Y%m")
#[1] "201612"

NOTE: No external packages used

akrun
  • 874,273
  • 37
  • 540
  • 662