R - keep order when using matching operators (% to%)

I use the appropriate operators to capture the values ​​that appear in the matrix from a separate data frame. However, the resulting matrix has values ​​in the order in which they appear in the data frame, and not in the original matrix. Is there a 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]

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

Thank!

+5
source share
3 answers

Use match.

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

, vec rownames(df), match .

Edit: , :

df[vec, ]
# [1] 2 1 3
+6

match ( NA , )

Filter(function(x) !is.na(x), match(rownames(df), vec))
+3

, :

'%ino%' <- function(x, table) {
    xSeq <- seq(along = x)
    names(xSeq) <- x
    Out <- xSeq[as.character(table)]
    Out[!is.na(Out)]
}

:

df[rownames(df) %ino% vec, 1]
[1] 2 1 3

() , as.character(), , % ino% :

LETTERS[1:26 %in% 4:1]
[1] "A" "B" "C" "D"


LETTERS[1:26 %ino% 4:1]
[1] "D" "C" "B" "A"

% in% :

LETTERS[1:26 %in% 3:-5]
[1] "A" "B" "C"

LETTERS[1:26 %ino% 3:-5]
[1] "C" "B" "A"

With% in%, the logical sequence is repeated by the size of the subset of the object, this does not apply to% ino%:

data.frame(letters, LETTERS)[1:5 %in% 3:-5,] 

    letters LETTERS
 1        a       A
 2        b       B
 3        c       C
 6        f       F
 7        g       G
 8        h       H
 11       k       K
 12       l       L
 13       m       M
 16       p       P
 17       q       Q
 18       r       R
 21       u       U
 22       v       V
 23       w       W
 26       z       Z


data.frame(letters, LETTERS)[1:5 %ino% 3:-5,]

   letters LETTERS
 3       c       C
 2       b       B
 1       a       A
0
source

All Articles