mi3567
mi3567

Reputation: 79

How to extract some characters based on certain patterns from a vector?

Here are the data

x <- c("a01|a44;b013|b021|c35;c014|c035|c078")
y <- c("a03|a41;b033|b021|72;c014|c031|c078")
z <- c("a01|a44;c014|c035|c078;b013|b021|d35|c33")
v <- c(x, y, z)

I want to extract the third element separated by "|" from a string starting with "b0". The expected result is c35,72,d35.

Upvotes: 2

Views: 39

Answers (1)

akrun
akrun

Reputation: 887951

We can try

sapply(strsplit(v, ';'), function(x) 
       sapply(strsplit(x[grep('^b0', x)], '[|]'), `[`,3))
 #[1] "c35" "72"  "d35"

Or use sub

 sub('.*;b0\\d{2}\\|[^|]+\\|([^;|]+).*', '\\1', v)
 #[1] "c35" "72"  "d35"

Upvotes: 1

Related Questions