Reputation: 273
I am trying to replace the complete string if the two characters matches.Below is the code I am using in R
st <- "arzo"
ret <- gsub("^ar","honor8",st)
However it replacing only the portion where it find ar and giving the below output
honor8zo
Is there a way to replace complete string if two characters matches
Upvotes: 0
Views: 457
Reputation: 1536
Just add .*
to replace the whole string:
ret <- gsub("^ar.*","honor8",st)
Upvotes: 2
Reputation: 1975
Using grep, in 1 line
st <- c("aaaa", "arzo", "bbb")
st[grep("^ar",st)] <- "honor8"
st
Upvotes: 0
Reputation: 39154
We can use grepl
to detect the presence of target strings, and then replace them. I added two more strings (foo
, bar
) to st
to show that this approach will only replace the complete string if the condition (^ar
) is met. ret
is the result of replacement.
st <- c("arzo", "foo", "bar")
ret <- st
ret[grepl("^ar", ret)] <- "honor8"
ret
[1] "honor8" "foo" "bar"
Upvotes: 1