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

Gabor Grothendieck ggrothendieck at gmail.com
Tue Sep 26 03:41:41 CEST 2006

```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 at 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 at 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?
> >
> >
> > FD
> >
> >        [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help