Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting values after pattern

Tags:

r

A beginner question...

I have a list like this:

x <- c("aa=v12, bb=x21, cc=f35", "xx=r53, bb=g-25, yy=h48", "nn=u75, bb=26, gg=m98")

(but many more lines)

I need to extract what is between "bb=" and ",". I.e. I want:

x21  
g-25  
26  

Having read many similar questions here, I suppose it is stringr with str_extract I should use, but somehow I can't get it to work. Thanks for all help.

/Chris

like image 867
Chris Avatar asked Sep 11 '26 10:09

Chris


1 Answers

strapply in the gsubfn package can do that. Note that [^,]* matches a string of non-commas.

strapply extracts the back referenced portion (the part within parentheses):

> library(gsubfn)
> strapply(x, "bb=([^,]*)", simplify = TRUE)
[1] "x21"  "g-25" "26"  

If there are several x vectors then provide them in a list like this:

> strapply(list(x, x), "bb=([^,]*)")
[[1]]
[1] "x21"  "g-25" "26"  

[[2]]
[1] "x21"  "g-25" "26"
like image 68
G. Grothendieck Avatar answered Sep 12 '26 23:09

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!