A base variant similar to the method from @G.Grothendieck and @margusl using gregexpr
to find the positions of Y
, S
or T
and using regmatches<-
, like @onyambu, to insert p
at this positions.
sIn <- function(s, i) {
`regmatches<-`(rep(s, length(i)), `attr<-`(i, "match.length", 0), value="p")
}
Map(sIn, s, gregexpr("[YST]", s))
#[[1]]
#[1] ""
#
#$ABC
#[1] "ABC"
#
#$YSAHEEHHYDK
#[1] "pYSAHEEHHYDK" "YpSAHEEHHYDK" "YSAHEEHHpYDK"
#
#$HEHISSDYAGK
#[1] "HEHIpSSDYAGK" "HEHISpSDYAGK" "HEHISSDpYAGK"
#...
Or using str_sub<-
and str_locate_all
from stringr
with a non consuming look ahead (?=[YST])
.
library(stringr)
Map(`str_sub<-`, s, str_locate_all(s,"(?=[YST])"), value="p")
#[[1]]
#character(0)
#
#$ABC
#character(0)
#
#$YSAHEEHHYDK
#[1] "pYSAHEEHHYDK" "YpSAHEEHHYDK" "YSAHEEHHpYDK"
#
#$HEHISSDYAGK
#[1] "HEHIpSSDYAGK" "HEHISpSDYAGK" "HEHISSDpYAGK"
#...
Or the same but using stringi
.
library(stringi)
Map(`stri_sub<-`, s, stri_locate_all(s, regex="(?=[YST])"), value="p")
#[[1]]
#[1] NA
#
#$ABC
#[1] NA
#
#$YSAHEEHHYDK
#[1] "pYSAHEEHHYDK" "YpSAHEEHHYDK" "YSAHEEHHpYDK"
#
#$HEHISSDYAGK
#[1] "HEHIpSSDYAGK" "HEHISpSDYAGK" "HEHISSDpYAGK"
#...
Data (added the first two strings like @G.Grothendieck)
s <- c("", "ABC", "YSAHEEHHYDK", "HEHISSDYAGK", "TFAHTESHISK", "ISLGEHEGGGK",
"LSSGYDGTSYK", "FGTGTYAGGEK", "VGASTGYSGLK", "TASGVGGFSTK",
"SYASDFGSSAK", "LYSYYSSTESK")