sai kamal
sai kamal

Reputation: 61

How to replace only 2nd character from a string in R

s<-"HsdKjnsjsHLKsmH"

how to substitute a character at a particular position in R replace only second "H" in the string s with "Q"

Upvotes: 1

Views: 894

Answers (3)

acylam
acylam

Reputation: 18681

We can use gregexpr and substr. gregexpr finds all matches and returns the position of the matches. Using the position of the second match, we can then replace the second "H" with "Q" using substr. This guarantees that it's always the second "H" that we're replacing:

s = "HsdKjnsjsHLKsmH"

pos <- gregexpr("H", s)[[1]][2]

substr(s, pos, pos) <- "Q"
# [1] "HsdKjnsjsQLKsmH"

Another method using stringr, and making it a :

library(stringr)

str_pos_replace <- function(string, pattern, replacement, pos=1){
  str_locate_all(string, pattern)[[1]][pos,, drop=FALSE] %>%
    `str_sub<-`(string, ., value = replacement)
}

str_pos_replace(s, "H", "QQQ", 2)
# [1] "HsdKjnsjsQQQLKsmH"

Upvotes: 4

Andre Elrico
Andre Elrico

Reputation: 11480

s = "HsdKjnsjsHLKsmH"
sub("[^H]*H[^H]*\\KH","Q",s,perl=T)


#[1] "HsdKjnsjsQLKsmH"

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76460

Try the following.

s <- "HsdKjnsjsHLKsmH"
sub("(H[^H]*)H", "\\1Q", s)

If you want to generalize the code above, here is a function that does so.

replaceSecond <- function(s, old, new){
    pattern <- paste0("(", old, "[^", old, "]*)", old)
    new <- paste0("\\1", new)
    sub(pattern, new, s)
}

replaceSecond(s, "H", "Q")
#[1] "HsdKjnsjsQLKsmH"

Upvotes: 1

Related Questions