Search code examples
rstringsubstringstringr

Changing the format of pairs of years in a vector in R


I was wondering if it might be possible to change the format of my Input to my Desired_output?

Input= c("20192020","20202021","20212022")

Desired_output= c("2019-20","2020-21","2021-22")

Solution

  • We can use sub() here:

    Input <- c("20192020", "20202021", "20212022")
    out <- sub("\\d{2}(\\d{2})$", "-\\1", Input)
    out
    
    [1] "2019-20" "2020-21" "2021-22"