1

I have integer data example like this

201901, 201912, 202004

How to convert my data into year and month using R Programming. I need output like this:

2019-01, 2019-12, 2020-04

or

Jan-2019, Dec-2019, Apr-2020

Thank you in advance.

Hoppo
  • 1,130
  • 1
  • 13
  • 32
aruz33
  • 13
  • 3

1 Answers1

2

You can convert to date and then use format :

x <- c(201901, 201912, 202004)

format(as.Date(paste(x, '01'), '%Y%m%d'), '%b-%Y')
#[1] "Jan-2019" "Dec-2019" "Apr-2020"
format(as.Date(paste(x, '01'), '%Y%m%d'), '%Y-%m')
#[1] "2019-01" "2019-12" "2020-04"

You can also use zoo's yearmon :

zoo::as.yearmon(as.character(x), '%Y%m')

Using regex we can capture 4 and 2 characters and insert a "-" in between.

sub('(.{4})(.{2})', '\\1-\\2', x)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213