Change first two characters in string in R

1.1k views Asked by At

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"
2

There are 2 answers

0
akrun On BEST ANSWER

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"
0
moseno On

@grrgrrbla thanks, but in my case this is not suitable. I has escaped from numerical transformation cause transformation to numerical variable omits 0. Another example with 0* hours

> time <-  c("053500", "053800", "061400", "061700", "163000", "161800", "201700", "201800")
> from <- c("05", "06", "16", "20")
> test[substr(time, 1, 2) %in% from] <-
+ as.character(as.numeric(time[substr(time, 1, 2) %in% from]) - 50000)
> cbind(time, test)
     time     test    
[1,] "053500" "3500"  
[2,] "053800" "3800"  
[3,] "061400" "11400" 
[4,] "061700" "11700" 
[5,] "163000" "113000"
[6,] "161800" "111800"
[7,] "201700" "151700"
[8,] "201800" "151800"

These characters makes a trouble to add colon(h:m:s) and "0" where it is needed to use time format.