Getting rid of white space at the beginning and end of a string

July 28, 2011

(This article was first published on Software for Exploratory Data Analysis and Statistical Modelling » R Environment, and kindly contributed to R-bloggers)

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:


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.

To leave a comment for the author, please follow the link and comment on their blog: Software for Exploratory Data Analysis and Statistical Modelling » R Environment. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

plotly webpage

dominolab webpage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training




CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)