s-news
[Top] [All Lists]

Re: Trimming character strings

To: Thom Burnett <Thom.Burnett@cognigencorp.com>
Subject: Re: Trimming character strings
From: Sundar Dorai-Raj <sundar.dorai-raj@pdf.com>
Date: Thu, 27 Jan 2005 14:09:35 -0600
Cc: S-News <s-news@lists.biostat.wustl.edu>
In-reply-to: <41F94148.5000506@cognigencorp.com>
Organization: PDF Solutions, Inc.
References: <41F94148.5000506@cognigencorp.com>
User-agent: Mozilla Thunderbird 1.0 (Windows/20041206)


Thom Burnett wrote:
This should be quick and easy for someone.

How do I remove leading and trailing white space from a string?

nameWithSpaces <- "  John Doe  "
onlyName <- whatFunction(nameWithSpaces)
onlyName
"John Doe"

I thought I saw a function for this some month or so ago but now I can't find anything short of using substring one character at a time.

Thanx for any help.

Thom



In S-PLUS 6, there is ?regexpr.replace, so you can try:

tmp <- regexpr.replace("^[ \t]+", nameWithSpaces, "")
regexpr.replace("[ \t]+$", tmp, "")

I don't know how to do this in one step. However, in R this is much easier:

gsub("^[ \t]+|[ \t]+$", "", nameWithSpaces)

HTH,

--sundar


<Prev in Thread] Current Thread [Next in Thread>