Re: [R] Splitting a character variable into a numeric one and a character one?

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Mon 25 Sep 2006 - 16:37:44 GMT

On Mon, 2006-09-25 at 11:30 -0500, Marc Schwartz (via MN) wrote:
> On Mon, 2006-09-25 at 11:04 -0500, Frank Duan wrote:
> > Hi All,
> >
> > I have a data with a variable like this:
> >
> > Column 1
> >
> > "123abc"
> > "12cd34"
> > "1e23"
> > ...
> >
> > Now I want to do an operation that can split it into two variables:
> >
> > Column 1 Column 2 Column 3
> >
> > "123abc" 123 "abc"
> > "12cd34" 12 "cd34"
> > "1e23" 1 "e23"
> > ...
> >
> > So basically, I want to split the original variabe into a numeric one and a
> > character one, while the splitting element is the first character in Column
> > 1.
> >
> > I searched the forum with key words "strsplit"and "substr", but still can't
> > solve this problem. Can anyone give me some hints?
> >
> > Thanks in advance,
> >
> > FD
>
>
> Something like this using gsub() should work I think:
>
> > DF
> V1
> 1 123abc
> 2 12cd34
> 3 1e23
>
>
> # Replace letters and any following chars with ""
> DF$V2 <- gsub("[A-Za-Z]+.*", "", DF$V1)

Quick typo correction here. It should be:

DF$V2 <- gsub("[A-Za-z]+.*", "", DF$V1)

The second 'z' should be lower case.

Marc



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue Sep 26 02:41:44 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 25 Sep 2006 - 17:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.