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 add a value inside a string

How can I add a value inside a string when a condition is met.

For example, take the following data:

my_data <- c("ab 93 1455 1863 2713 sb 673 771 1601 1969", 
             "ab 93 1098 1455 2423 2427 sb 168 673 1256", 
             "ab 93 1098; sb 1256")

I want to add a ";" when a number proceeds a character.

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

Therefore, I would like the output to be:

output<- c("ab 93 1455 1863 2713; sb 673 771 1601 1969", 
           "ab 93 1098 1455 2423 2427; sb 168 673 1256", 
           "ab 93 1098; sb 1256")

If this solution could be completed in the context of a data frame that would be great.

So far, I have been able to detect the condition I’m interested in using the following code:

str_detect(my_data, "[0-9] [a-z]")
[1]  TRUE  TRUE FALSE

But I am having trouble moving beyond this point.

Thank you for the help!

>Solution :

Of course, use regular expressions:

output <- gsub("(\\d)( +[a-zA-Z])", "\\1;\\2", my_data)

print(output)

# [1] "ab 93 1455 1863 2713; sb 673 771 1601 1969" "ab 93 1098 1455 2423 2427; sb 168 673 1256"
# [3] "ab 93 1098; sb 1256"        
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