Subtract months from time in format year-month

2.7k views Asked by At

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?

2

There are 2 answers

0
Ronak Shah On BEST ANSWER

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"
3
akrun On

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