0

I have a monthly data, where first six colums are stable, but the rest of columns represent months and are named respectively (column called 01.2019 representing January 2019 and so on). I would like to change names of all these monthly colums (both existing and coming, because data will be updated monthly) so that for example above mentioned column "01.2019" would be column " 201901". I have tried several gsub()-variations already, but with poor results.

Phh
  • 7
  • 1
  • `sub("(\\d{1,2})\\.(\\d{4})", "\\2\\1", "01.2019")`. – Rui Barradas Oct 05 '19 at 12:16
  • It would be helpful if you included a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and some example of what you've tried even if it didn't work – camille Oct 05 '19 at 17:31

1 Answers1

0

Try the following regular expression.

m <- "01.2019"
sub("(\\d{2})\\.(\\d{4})", "\\2\\1", m)
#[1] "201901"

Explanation.

  1. \\d{2} exactly two digits, matches the month number.
  2. (\\d{2}) first capture group.
  3. \\. the character ., needs to be escaped since it's a meta character.
  4. \\d{4} exactly 4 digits, matches the year.
  5. (\\d{4}) second capture group.

Then, in the replacement pattern, just swap the capture groups, \\2 followed by \\1.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66