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 replace a string defined by starting and ending index by another string in R?

string <- "this is a funny cat"

I want to replace the first 15 characters of string with ‘orange`. The desired output is

'orange cat'

However, using substr gives me

substr(string, 1, 15) <- "orange"
> string
[1] "oranges a funny cat"

which is not the desired output.

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

>Solution :

The output of substr should be the pattern of sub.

string <- "this is a funny cat"

sub(substr(string, 1, 15), "orange", string)
[1] "orange cat"

Or directly replace the first 15 characters in sub.

sub("^.{15}", "orange", string)
[1] "orange cat"
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