Vector sorting: match, rank, order, sort, rev

First look makeup match function

matchFunction has four parameters.
match(x, table, nomatch = NA_integer_, incomparables = NULL)
x: Indicates that the query objects
table: indicates the matching value, may be in the form of a vector
nomatch: If no match the value returned, the default is NA
incomparables: setting an invalid value matching parameter table, the default setting is not (NULL)

By default, in order to match the tag does not match the return NA

x <- c("A","A","B","B","C","D")
match(x,c("A","C","B"))
#[1] 1 1 3 3 2 NA

Nomatch parameter setting, so as not to match returns 0

match(x,c("A","C","B"),0)
#[1] 1 1 3 3 2 0

Set incomparables parameters, ignoring C

match(x,c("A","C","B"),incomparables = "C")
#[1]1  1  3  3 NA NA

Note: Although set to ignore C, but it is still involved in ranking, so the results only 1,3, 2 no.

If two vector elements identical but in a different order, how to rearrange

x <- c("A","B","C","D","E")
y <- c("B","D","E","A","C")  
match(x,y)
#[1] 4 1 5 2 3
y[match(x,y)]  
#[1] "A" "B" "C" "D" "E"

Since it involves the sort to tell you rank, order, sort
fact, the earlier example can be directly sort(y)addressed.

rank(c(3,1,2,5,4))
#[1] 3 1 2 5 4
order(c(3,1,2,5,4))
#[1] 2 3 1 5 4
sort(c(3,1,2,5,4))
#[1] 1 2 3 4 5
rev(c(3,1,2,5,4))
#[1] 4 5 2 1 3

rank return value means: the original vector of the first element row 3, the second element of a first row, and so on.
order means the return value: the minimum value of 2, the next smallest value of the bit in the third. . . The maximum value at position 4
is relatively simple sort, I sent a small to large order.
rev is the vector elements output from back to front.

More intuitive look, with just an example of y

rank(y)
#[1] 2 4 5 1 3
order(y)
#[1] 4 1 5 2 3
sort(y)
#[1] "A" "B" "C" "D" "E"
rev(y)
#[1] "C" "A" "E" "D" "B"

Reproduced in: https: //www.jianshu.com/p/fba990bde546

Guess you like

Origin blog.csdn.net/weixin_33850890/article/details/91071337