Nikita Vlasenko
Nikita Vlasenko

Reputation: 4352

Order one vector of strings by partial match of the other

I have two vectors of strings and I need to order one vector by partial match of the other. The vectors look like that:

enter image description here

So, I need to take each element of the first vector and find its position in names in order for both vectors to be in the same order. For instance GF1 should be 9th element in the first vector. I know how to order things once the ordering is known. I tried match function but it is not working returning me NAs:

names_order <- match(paste0(samples$groups, samples$mouse), names)

I tried also pmatch with no success. Probably because match searches for full matches. Grepl function is not working either:

grep(paste0(paste0(samples$groups, samples$mouse), collapse = '|'), names, value = TRUE)

Returns just [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 which is just where the match is found without the ordering I need.

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 935

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520918

Here is one way using grep and sapply:

samples$mouse[sapply(samples$groups, function(x) { grep(x, samples$mouse) })]

The grep base R function is not vectorized with regard to the first parameter, so we can't feed in the entire groups vector. Instead, we can use sapply to find the indices of matches in the mouse vector of paths.

Upvotes: 2

Related Questions