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 the white space after a number with a delimiter in R

I have a number of different values in a column that all represent customer (see the an example below)

What I’m looking to do is if a space (" ") comes after the customer "number" then replace that space with a ",". Otherwise, don’t replace it, as there are some instances where a customer name has a space in it and I’d like to keep that.

Example:

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

data.frame(customer = c("HOSPITAL FUN:12456 HOSPITAL:23456",
                       "MEDICAL GR:78988 MEDICAL ABC:98778 MEDICAL:90808"))

I’d like it to look like

data.frame(customer = c("HOSPITAL FUN:12456,HOSPITAL:23456",
                       "MEDICAL GR:78988,MEDICAL ABC:98778,MEDICAL:90808"))

My thought is that if I could look for a space coming after a number and replace that it would work but I’m not sure what the expression would be. Any help woudl be greatly appreciated! Thanks

>Solution :

Using gsub with replacement group \\1

data.frame(lapply(df, gsub, pattern="(\\d+) ", replacement="\\1,"))
                                          customer
1                HOSPITAL FUN:12456,HOSPITAL:23456
2 MEDICAL GR:78988,MEDICAL ABC:98778,MEDICAL:90808
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