removing trailing spaces with gsub in R

MikeTP picture MikeTP · May 8, 2012 · Viewed 22.2k times · Source

Does anyone have a trick to remove trailing spaces on variables with gsub?

Below is a sample of my data. As you can see, I have both trailing spaces and spaces embedded in the variable.

county <- c("mississippi ","mississippi canyon","missoula ",
            "mitchell ","mobile ", "mobile bay")  

I can use the following logic to remove all spaces, but what I really want is to only move the spaces at the end.

county2 <- gsub(" ","",county)

Any assistance would be greatly appreciated.

Answer

Joshua Ulrich picture Joshua Ulrich · May 8, 2012

Read ?regex to get an idea how regular expressions work.

gsub("[[:space:]]*$","",county)

[:space:] is a pre-defined character class that matches space characters in your locale. * says to repeat the match zero or more times and $ says to match the end of the string.