Duck Duck - 10 months ago 37
R Question

Replace white space in string only when there are two or more white spaces

I am working with strings in

. I have the next string:

x<-c("Alfa Cactus 500 Bachelor degree Star")

For example, in this string after the first word I have two spaces. After the second word I have three spaces. I am trying to replace only white spaces when there are two or more of them. In that case I would like to add
instead of white spaces. I am looking for a new string like this:

Alfa*Cactus*500*Bachelor degree*Star

In the case of
Bachelor degree
I only have one white space. Then, the replace must not be done. When I try this:

gsub(" +","*",x)

I got this:


But, It is not respected the fact that only one white space must not be replaced. I do not know how to adapt
to perform this change.

I hope you can help me with this. Thanks a lot of.


You need two spaces.

gsub("  +","*",x)
[1] "Alfa*Cactus*500*Bachelor degree*Star"