pak
pak

Reputation: 855

sort vector based on another partial matching vector

I have two character vectors A and B. Most of A has matching strings in B, matched by the first 6 characters. A strings always end with 'd', and B strings always ends with 'z'. I'd like to sort B based on A, and put any non-matches in C.

Original data:

A <- c("ABCD01d", "DEFG10d", "ZYXW43d")
B <- c("ABCD01z", "ZYXW43z", "DEFG10z", "DFGS88z")

I'd like to end up with:

A <- c("ABCD01d", "DEFG10d", "ZYXW43d")
B <- c("ABCD01z", "DEFG10z", "ZYXW43z")
C <- c("DFGS88z")

What's the best way to do this?

Upvotes: 1

Views: 448

Answers (1)

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12819

Try this:

m <- match(substr(B,1,6), substr(A,1,6))
B[na.exclude(m)]
#[1] "ABCD01z" "DEFG10z" "ZYXW43z"
B[is.na(m)]
#[1] "DFGS88z"

Upvotes: 2

Related Questions