简体   繁体   English

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

[英]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') :对于年月向量: 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?", "")

Out:出去:

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

How could I remove the leading zeros from the single digit months?如何从个位数月份中删除前导零? Thanks.谢谢。

Using paste , date format isn't of much interest and would just produce overhead.使用paste ,日期格式不是很感兴趣,只会产生开销。

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

Using gsub :使用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

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM