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:
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