Removing Spaces in R


Sometimes you have extra spaces in your text string. You need to clean that up.

test <- " Hi,  this has too     many spaces. "
new <- gsub("\\s+"," ",test)
newer <- trimws(new)

trimws() removes leading and trailing spaces. gsub() will remove extra spaces in the middle. You may have noticed that gsub() uses regular expressions.

Leave a Reply