Remove leading zeros from single digit months in year-month values

Viewed 197

For year month vector: year_months <- c('2021-12', '2021-11', '2021-02', '2021-01'), I try to use the following code to convert year_months to c('2021Y12m', '2021Y11m', '2021Y2m', '2021Y1m') :

format(as.Date(lubridate::ym(year_months)), "%YY%mm")

stringr::str_replace_all(format(as.Date(lubridate::ym(year_months)), "%YY%mm"), "-0?", "")

Out:

[1] "2021Y12m" "2021Y11m" "2021Y02m" "2021Y01m"

How could I remove the leading zeros from the single digit months? Thanks.

3 Answers

Using paste, date format isn't of much interest and would just produce overhead.

sapply(strsplit(year_months, '-'), \(x) 
       paste(paste0(as.numeric(x), c('Y', 'm')), collapse=''))
# [1] "2021Y12m" "2021Y11m" "2021Y2m"  "2021Y1m" 

Using gsub:

gsub("Y0", "Y", format(as.Date(lubridate::ym(year_months)), "%YY%mm"))
# [1] "2021Y12m" "2021Y11m" "2021Y2m"  "2021Y1m" 

Or stringr::str_replace_all:

stringr::str_replace_all(format(as.Date(lubridate::ym(year_months)), "%YY%mm"), "Y0", "Y")
# [1] "2021Y12m" "2021Y11m" "2021Y2m"  "2021Y1m" 

You could also do:

format(as.Date(paste0(year_months, '-01'), format = '%Y-%m-%d'), '%YY%mm')

which will generate:

#"2021Y12m" "2021Y11m" "2021Y02m" "2021Y01m"
Related