Search code examples
rsubstr

Change first two characters in string in R


In R, I would like to find and replace two characters in string (just first two characters) Here are the data I start with.

time <-  c("153500", "153800", "161400", "161700", "163000", "161800", 
                "201700", "201800")

from <- c("15", "16", "17", "18")
to <- c("10","11", "12", "13" )
repl <- data.frame(from, to) 

the result should look like this:

[1] "103500" "103800" "111400" "111700" "113000" "111800" "201700" "201800"

Solution

  • Try

    v1 <- setNames(to, from)[substr(time, 1, 2)]
    as.character(ifelse(!is.na(v1), paste0(v1, sub('^.{2}','', time)), time))
    #[1] "103500" "103800" "111400" "111700" "113000" "111800" "201700" "201800"