HiveRLearner
HiveRLearner

Reputation: 107

Inserting a char at specific location in R character string

I have a R string like this

a <- "(hi I am (learning R) )" 

I want to add a character "x" in above string and make it like

"(hi I am (learning R)x )" 

How can I do that using R efficiently?

Edit : Adding 1 more information: Assume that the pattern can change for starting character string but last 2 bracket in the end will remain same all the time and I have to insert x between them all the time.

Upvotes: 1

Views: 4542

Answers (1)

akuiper
akuiper

Reputation: 214957

You can use sub, capture the unique pattern that you want to insert after and then use back reference to add x:

sub("(R\\))", "\\1x", a)
# [1] "(hi I am (learning R)x )"

Update on inserting character between two brackets at the end of the string, the simplest would be match a pattern and replace it with your desired one:

sub("\\) \\)$", "\\)x \\)", a)
# [1] "(hi I am (learning R)x )"

Upvotes: 3

Related Questions