[R] R string help

Gabor Grothendieck ggrothendieck at gmail.com
Tue Feb 1 19:14:27 CET 2011


On Tue, Feb 1, 2011 at 12:42 PM, Yan Jiao <y.jiao at ucl.ac.uk> wrote:
> Dear R guru:
>
>
>
> If I got a variable
>
> aaa<- "up.6.11(16)"
>
>
>
> how can I extract 16 out of the bracket?
>
> I could use substr, e.g.
>
> substr(aaa, start=1, stop=2)
>
> [1] "up"
>
>
>
> But it needs start and stop, what if my start or stop is not fixed, I
> just want the number inside the bracket, how can I achieve this?
>

strapply in gsubfn is intended for that type of problem.

1. The regular expression matches an open parenthesis "\\(" any string
".*" and then a close parenthesis "\\)" sending the portion within
unescaped parentheses (...) to the as.numeric function.

> library(gsubfn)
> aaa<- "up.6.11(16)"
> strapply(aaa, "\\((.*)\\)", as.numeric, simplify = TRUE)
[1] 16

2. If you knew it was at the end then the simpler regular expression
"(\\d+).$" would also work

> strapply(aaa, "(\\d+).$", as.numeric, simplify = TRUE)
[1] 16

3. or we could extract all the numbers and take the last one:

> strapply(aaa, "\\d+", as.numeric, simplify = ~ tail(x, 1))
[1] 16


See: http://gsubfn.googlecode.com

-- 
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