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.
trimws() function is used to remove or strip, leading and trailing space of the column in R.
gsub() function is used to remove the space by removing the space in the given string.
You can use the STRIP function to remove both the leading and trailing spaces from the character strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With