[R] Extracting only one part of an string

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Nov 19 09:15:20 CET 2007


On Mon, 19 Nov 2007, Benilton Carvalho wrote:

> I'd use:
>
> sapply(strsplit(Names, "-"), "[[", 1)

An alternative is

sub("([^-]*).*", "\\1", Names)

which for many Names would be considerably more efficient.


> On Nov 19, 2007, at 2:14 AM, Tom.O wrote:
>
>>
>> Hi
>> I wonder if there's a smarter way to do this procedure.
>>
>> I have a vector of filenames wher  I only am interested in the first
>> part of
>> the filename.
>> I would use the following method of extracting the first part. But
>> is there
>> a more simple way of doing this?
>>
>> Names <-
>> c("A1-F1.txt","A2-F1.txt","AB1-F1.txt","A1-F2.txt","AB1-F2.txt","B1-
>> F2.txt")
>> #..
>> temp <- strsplit(Names,"-")
>> temp <- unlist(temp)
>> temp <- temp[seq(from=1,to=2*length(Names),by=2)]
>>
>>> temp
>> [1] "A1"  "A2"  "AB1" "A1"  "AB1" "B1"
>>
>> Thanks for any feedback.
>> Regards Tom

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list