Add "\\-" every "x" letters of a string vector

Viewed 65

I have a date vector like this

date <- c("01jan2020", "04mar2020", "20dec2020")

and I want to separate it with - following the next pattern (after the first 2 digits and after the first 5 digits):

date_transform1 <- c("01-jan-2020", "04-mar-2020", "20-dec-2020")

Next I want to convert the first letter of the month into a capital letter:

date_transform2 <- c("01-Jan-2020", "04-Mar-2020", "20-Dec-2020")

Any clue?

Regards

3 Answers

You can try this approach splitting your text chain into multiple components:

#Data
date <- c("01jan2020", "04mar2020", "20dec2020")
#Extract first element
x1 <- substr(gsub("[^0-9.-]", "", date),1,2)
#Extract second element
x2 <- substr(gsub("[^0-9.-]", "", date),nchar(gsub("[^0-9.-]", "", date))-3,
             nchar(gsub("[^0-9.-]", "", date)))
#Format month
x3 <- gsub('[[:digit:]]+', '', date)
x3 <- paste(toupper(substr(x3, 1, 1)), substr(x3, 2, nchar(x3)), sep="")
#Now concatenate
xf <- paste0(x1,'-',x3,'-',x2)

Output:

[1] "01-Jan-2020" "04-Mar-2020" "20-Dec-2020"

You can convert the character object to Date and change its format.

format(as.Date(date, "%d%b%Y"), "%d-%b-%Y")

# [1] "01-Jan-2020" "04-Mar-2020" "20-Dec-2020"

The first letters of months will be turned to capital ones. You can also use dmy() from lubridate or anydate() from anytime to parse Date objects.

format(lubridate::dmy(date), "%d-%b-%Y")
format(anytime::anydate(date), "%d-%b-%Y")

Another option with stringr package:

library(stringr)

str_replace(date, "[a-z]+", function(x) sprintf("-%s-", str_to_title(x)))

# [1] "01-Jan-2020" "04-Mar-2020" "20-Dec-2020"

or

str_replace(date, "[a-z]+", function(x) str_pad(str_to_title(x), 5, "both", "-"))

# [1] "01-Jan-2020" "04-Mar-2020" "20-Dec-2020"

An option with lubridate and format

library(lubridate)
format(dmy(date), "%d-%b-%Y")
#[1] "01-Jan-2020" "04-Mar-2020" "20-Dec-2020"
Related