Re: [R] separate a variable in several variables

From: Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk_at_idi.ntnu.no>
Date: Wed, 12 Nov 2008 23:15:31 +0100

CE.KA wrote:
>
> x
> 1 12F
> 2 13 AD
> 3 356PO
> 4 1D
> 5 GRT
> 6 PO52
> 7 LN4Z
>
> Is there a way to separarate x in 2 variables:
> y: only numeric caracters
> z: only alpha caracters
> For exemple:
> x y z
> 1 12F 12 F
> 2 13 AD 13 AD
> 3 356PO 356 PO
> 4 1D 1 D
> 5 GRT 0 GRT
> 6 PO52 52 PO
> 7 LN4Z 4 LNZ
>
>

if you need it quickly, here is a hack. there may be better ways.

# some rubbish data
d = data.frame(x = replicate(10, paste(sample(c(letters, 0:9, " "), 10), collapse="")))

patterns = paste("[", c("^", ""), "A-Za-z]| ", sep="")

for (i in 1:2) d[patterns[i]] = gsub(patterns[i], "", d$x)

tweak the regex patterns accordingly to your demand for whitespace etc. rename the columns as you like.

vQ



R-help_at_r-project.org 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 Wed 12 Nov 2008 - 22:17:31 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 13 Nov 2008 - 11:30:24 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.

list of date sections of archive