[R] separate a variable in several variables
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Nov 12 23:15:31 CET 2008
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
More information about the R-help
mailing list