Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform replacements containing square brackets with string_replace()?

I have a vector with two elements:

xx <- c("K[Phenylisocyanate (N-term)]SAPATGGVKKPHR", "A[Phenylisocyanate (N-term)]SAPATGGVKKPHR")

I would like to replace "[Phenylisocyanate (N-term)]" with "[Phenylisocyanate_Propionyl (Nterm)]", but only if the part to be replaced ("[Phenylisocyanate (N-term)]") is preceded by "K", i.e. in the first element only

So I would like to get c("K[Phenylisocyanate_Propionyl (Nterm)]SAPATGGVKKPHR", "A[Phenylisocyanate (N-term)]SAPATGGVKKPHR").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Performing this replacement with

str_replace (xx,  "K[Phenylisocyanate (N-term)]", "K[Phenylisocyanate_Propionyl (Nterm)]")

results in very unexpected behaviour:

[1] "K[Phenylisocyanate_Propionyl (Nterm)]Phenylisocyanate (N-term)]SAPATGGVKKPHR"

[2] "A[Phenylisocyanate (N-term)]SAPATGGVKK[Phenylisocyanate_Propionyl (Nterm)]HR"

could you perhaps explain how I should be writing this replacement and why I get this bizzare result?

>Solution :

The reason for the result above is that [ and ] are metacharacters in regular expressions, they mean ‘match any character that appears inside the square brackets’.

To get around this, you can use the fixed() function to tell R that the pattern is not a regular expression.

str_replace(xx,  fixed("K[Phenylisocyanate (N-term)]"), "K[Phenylisocyanate_Propionyl (Nterm)]")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading