Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing trailing spaces with gsub in R [duplicate]

Tags:

r

gsub

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.

like image 224
MikeTP Avatar asked May 08 '12 16:05

MikeTP


People also ask

How do I get rid of trailing blanks in R?

trimws() function is used to remove or strip, leading and trailing space of the column in R.

How do I get rid of extra spaces in R?

gsub() function is used to remove the space by removing the space in the given string.

Which function removes Allleading and trailing whitespaces Instring?

You can use the STRIP function to remove both the leading and trailing spaces from the character strings.


1 Answers

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.

like image 124
Joshua Ulrich Avatar answered Oct 23 '22 03:10

Joshua Ulrich