Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra white space between words inside a character vector using?

Tags:

regex

r

Suppose I have a character vector like

"Hi,  this is a   good  time to   start working   together.".  

I just want to have

" Hi, this is a good time to start working together."  

Only one white space between two words. How should I do this in R?

like image 508
Smith Black Avatar asked Oct 02 '13 00:10

Smith Black


People also ask

How do I get rid of extra white spaces in a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I get rid of white space in R?

trimws() function in R Language is used to trim the leading white spaces. It shrinks an object by removing outermost rows and columns with the same values.


1 Answers

gsub is your friend:

test <- "Hi,  this is a   good  time to   start working   together." gsub("\\s+"," ",test) #[1] "Hi, this is a good time to start working together." 

\\s+ will match any space character (space, tab etc), or repeats of space characters, and will replace it with a single space " ".

like image 131
thelatemail Avatar answered Sep 20 '22 17:09

thelatemail