[R] Extract number from string
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Feb 7 16:36:08 CET 2011
On Mon, Feb 7, 2011 at 9:37 AM, Roy Mathew <roymathew86 at gmail.com> wrote:
> Dear R Users,
>
> if I have a string as follows
> x<-"jsda23tth"
>
> How can I extract out 23 as a numeral?
> I found
> substr(x,5,6)
> but, this doesnt work if the number of alphabets differ.
>
> This is another example where the numbers need to be extracted.
> x<-c("jsda23tth","fgd54fgd","j3ngh","gfdjh564")
>
> any ideas?
>
> This didnt work.
> grep("[/d]",x)
Here are a couple of solutions:
> as.numeric(gsub("\\D", "", x))
[1] 23 54 3 564
> library(gsubfn)
> strapply(x, "\\d+", as.numeric, simplify = TRUE)
[1] 23 54 3 564
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list