从年月值中的个位数月份中删除前导零

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

对于年月向量:year_months <- c('2021-12', '2021-11', '2021-02', '2021-01'), 我尝试使用以下代码将 year_months 转换为 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?", "")

输出:

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

如何从个位数月份中删除前导零?谢谢。

使用 paste,日期格式没有多大意义,只会产生开销。

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

使用gsub:

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

stringr::str_replace_all:

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

你也可以这样做:

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

这将生成:

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