简体   繁体   中英

Using gsub in R to for conditional matching with multiple patterns

I'm trying to reformat a dynamic string that describes the day's date. Today's string is "December 6, 2020". Tomorrow it will be "December 7, 2020".

I'd like to reformat the string so that days of the month 1-9 are written "01", "02", etc.

The string is scraped, but for illustrative purposes let's just say:

lastupDate <- "December 6, 2020"

Below is a very clunky, repetitive way to reformat the string no matter the actual date:

lastupDATE <- gsub(" 1,", " 01,", lastupDATE)
lastupDATE <- gsub(" 2,", " 02,", lastupDATE)
lastupDATE <- gsub(" 3,", " 03,", lastupDATE)
lastupDATE <- gsub(" 4,", " 04,", lastupDATE)
lastupDATE <- gsub(" 5,", " 05,", lastupDATE)
lastupDATE <- gsub(" 6,", " 06,", lastupDATE)
lastupDATE <- gsub(" 7,", " 07,", lastupDATE)
lastupDATE <- gsub(" 8,", " 08,", lastupDATE)
lastupDATE <- gsub(" 9,", " 09,", lastupDATE)

This is pretty ugly. It does the trick, but I'm curious if anyone has a better idea.

Many thanks!

We can convert to Date class and then do the format

format(as.Date(lastupDate, '%B %d, %Y'), "%m %d, %Y")
#[1] "12 06, 2020"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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