r - Replace element in vector based on first letter of character string -


consider vectors below:

id <- c("a1","b1","c1","a12","b2","c2","av1")  names <- c("alpha","bravo","charlie","avocado") 

i want replace first character of each element in vector id vector names based on first letter of vector names. want add _0 before each number between 0:9.

note elements av1 , avocado throw things off bit, lowercase v in av1.

the result should this:

res <- c("alpha_01","bravo_01","charlie_01","alpha_12","bravo_02","charlie_02", "avocado_01") 

i know should done regex i've been trying 2 days , haven't got anywhere.

we can use gsubfn.

library(gsubfn) #remove number part 'id' (using `sub`) , unique elements nm1 <- unique(sub("\\d+", "", id)) #using gsubfn, replace non-numeric elements matching  #key/value pair in replacement #finally format add "_" sub sub("(\\d+)$", "_0\\1", gsubfn("(\\d+)", as.list(setnames(names, nm1)), id)) #[1] "alpha_01"   "bravo_01"   "charlie_01" "alpha_02"  #[5] "bravo_02"   "charlie_02" "avocado_01" 

the (\\d+) indicates 1 or more numeric elements, , (\\d+) 1 or more non-numeric elements. wrapping within brackets capture group , replace backreference (\\1 - first backreference captured group).

update

if condition append 0 'id's have numbers less 10, can second gsubfn , sprintf

gsubfn("(\\d+)", ~sprintf("_%02d", as.numeric(x)),                        gsubfn("(\\d+)", as.list(setnames(names, nm1)), id)) #[1] "alpha_01"   "bravo_01"   "charlie_01" "alpha_12"  #[5]  "bravo_02"   "charlie_02" "avocado_01" 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -