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

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 26 Sep 2006 - 01:41:41 GMT

Here is a slight simplification of the strapply solution using simplify = TRUE

library(gsubfn)
s <- c("123abc", "12cd34", "1e23")

out <- t(strapply(s, "^([[:digit:]]+)(.*)", c, simplify = TRUE)) # matrix data.frame(x = out[,1], num = as.numeric(out[,2]), char = out[,3])

On 9/25/06, Gabor Grothendieck <ggrothendieck@gmail.com> wrote:
> strapply in package gsubfn can do that:
>
>
> library(gsubfn)
> s <- c("123abc", "12cd34", "1e23")
>
> out <- strapply(s, "^([[:digit:]]+)(.*)", c)
> out <- do.call(rbind, out) # as a matrix
>
> data.frame(x = out[,1], num = as.numeric(out[,2]), char = out[,3]) #
> as a data.frame
>
>
> On 9/25/06, Frank Duan <fhduan@gmail.com> 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
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > 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.
> >
>



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 11:46:26 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 Tue 26 Sep 2006 - 02:30:08 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.