Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - preserve order when using matching operators (%in%)

Tags:

operators

r

I am using matching operators to grab values that appear in a matrix from a separate data frame. However, the resulting matrix has the values in the order they appear in the data frame, not in the original matrix. Is there any way to preserve the order of the original matrix using the matching operator?

Here is a quick example:

vec=c("b","a","c"); vec

df=data.frame(row.names=letters[1:5],values=1:5); df

df[rownames(df) %in% vec,1]

This produces > [1] 1 2 3 which is the order "a" "b" "c" appears in the data frame. However, I would like to generate >[1] 2 1 3 which is the order they appear in the original vector.

Thanks!

like image 724
jslefche Avatar asked May 14 '12 15:05

jslefche


1 Answers

Use match.

df[match(vec, rownames(df)), ]
# [1] 2 1 3

Be aware that if you have duplicate values in either vec or rownames(df), match may not behave as expected.

Edit: I just realized that row name indexing will solve your issue a bit more simply and elegantly:

df[vec, ]
# [1] 2 1 3
like image 109
bdemarest Avatar answered Sep 20 '22 23:09

bdemarest