Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Created May 31, 2022 13:45
Show Gist options
  • Save alekrutkowski/6596a43346cdbb9721b95ceae7a6d226 to your computer and use it in GitHub Desktop.
Save alekrutkowski/6596a43346cdbb9721b95ceae7a6d226 to your computer and use it in GitHub Desktop.
Additional functions extending the R package `eurodata`
library(magrittr)
monthToQuarter <- function(charvec, safe=TRUE) {
# monthToQuarter(c('2022M01','2022M02','2022M03','2022M04',
# NA_character_,'2022M12'))
# # "2022Q1" "2022Q1" "2022Q1" "2022Q2" NA "2022Q4"
if (safe)
stopifnot(all(grepl('^[1-2][0-9]{3}M[0-1][0-9]',
charvec) | is.na(charvec)))
yr <-
sub('(....)M..','\\1',charvec)
qr <-
sub('....M(..)','\\1',charvec) %>%
as.integer() %>%
{as.integer((. - 1)/3) + 1}
ifelse(is.na(charvec), NA_character_,
paste0(yr,'Q',qr))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment