Assume I have data in a CSV that I've imported in R. This is a simplified version- the real sheet has 4700 rows. There are months in 1 digits and there are months in 2 digits.
| | Posted.On |
|1| 5/18/2022 |
|2| 07/04/2022|
|3| 6/20/2022 |
I would like to change all months in 1 digits to 2 digits (e.g. 5/18/2022 to 05/18/2022). How can I do this?
CodePudding user response:
This sould be enough:
tibble(date = c('5/18/2022', '12/04/2022', '6/20/2022', '1/20/2022')) %>%
mutate(month = str_extract(date, '\\d '),
date = if_else(str_length(month) == 1 , paste0('0',date), date)) %>%
select(-month)
# # A tibble: 4 × 1
# date
# <chr>
# 1 05/18/2022
# 2 12/04/2022
# 3 06/20/2022
# 4 01/20/2022
CodePudding user response:
gsub()
can replace a single digit before the first /
with a zero-filled digit:
Posted.On <- c('5/18/2022', '07/04/2022', '6/20/2022')
want <- gsub('^(\\d{1}/)','0\\1', Posted.On)