Getting rid of white space at the beginning and end of a string
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
There are situations where we are working with character strings extracted from various sources and it can be annoying when there is white space at the beginning and/or end of the strings. This whitespace can cause problems when attemping to sort, subset or various other common operations.
The stringr package has a handy function str_trim (edited) that comes to the rescue and is straightforward to use. First up make sure that the package is available in the R session:
require(stringr) |
Here is a basic example with a simple string:
> " This is an example of whitespace. " [1] " This is an example of whitespace. " > str_trim(" This is an example of whitespace. ") [1] "This is an example of whitespace." |
As we can see this is very simple and is set up to work on a vector of character strings as well.
Other useful resources are provided on the Supplementary Material page. Visit here for more examples of string manipulation.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.