Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: change to the same character as the previous character in a string

Tags:

regex

char

r

Suppose I have a vector c('JKA1','BP9C','SSTQ3WA') and I want to change the character before the number to that very number, so that R returns 'JK11' 'B99C' 'SST33WA'. Is there anyway to do this with regex or am I better off using something other than R?

like image 609
dasf Avatar asked Mar 16 '23 15:03

dasf


1 Answers

Match the letter before the number and then capture the number through capturing group. Then replace the matched characters with \\1\\1 means double times of characters present inside the group index 1.

> x <- c('JKA1','BP9C','SSTQ3WA')
> gsub("[A-Za-z](\\d)", "\\1\\1", x)
[1] "JK11"    "B99C"    "SST33WA"

sub function would be enough for this case.

> sub("[A-Z](\\d)", "\\1\\1", x)
[1] "JK11"    "B99C"    "SST33WA"
like image 50
Avinash Raj Avatar answered Mar 19 '23 03:03

Avinash Raj