removing trailing spaces with gsub in R
gsub, r
Solution
You could use an regular expression:
county <- c("mississippi ","mississippi canyon","missoula ",
"mitchell ","mobile ", "mobile bay")
county2 <- gsub(" $","", county, perl=T)
`$` stand for the end of your text sequence, therefore only trailing spaces are matched. `perl=T` enables regular expressions for the match pattern. For more on regular expression see `?regex`.
Problem
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.