Search code examples
rlubridatestringras.date

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


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.


Solution

  • 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"