[R] Trimming in R

Ken Takagi katakagi at bu.edu
Wed Jul 7 16:50:14 CEST 2010


David Winsemius <dwinsemius <at> comcast.net> writes:

> 
> 
> On Jul 7, 2010, at 9:23 AM, Andrew Leeser wrote:
> 
> > I am looking for a way to trim leading and trailing spaces in a  
> > character
> > string in R. For example:
> >
> > "       this is random text        "
> >
> > should become:
> >
> > "this is random text".
> >
> > I have a short function to perform this task as follows:
> >
> > trim <- function(str){
> >        str <- sub("^ +", "", str)
> >        str <- sub(" +$", "", str)
> > }
> >
> > While this function does seem to work, I am curious if there's  
> > anything built
> > into R that I can use instead, as that would be preferable.
> 
> I have been using the trim function in package gdata. The code is  
> quite similar to yours.
> 

You could also use the substr() function, assuming that you know a priori how
many spaces are before and after the text:

str = "       this is random text        "
nchar(str)
substr(str, 8, 26) # 7 spaces before and 8 after the text you want to keep.

HTH,
Ken



More information about the R-help mailing list