向量排序:match,rank,order,sort,rev

先补课一下match函数

match函数有4个参数。
match(x, table, nomatch = NA_integer_, incomparables = NULL)
x:表示查询对象
table:表示匹配数值,可以是向量形式
nomatch:如果不匹配返回的数值,默认是NA
incomparables:设置table参数中无效的匹配值,默认不设置(NULL)

默认情况下,匹配到的按顺序标记,不匹配的返回NA

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

设置nomatch参数,使不匹配的返回0

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

设置incomparables参数,忽略C

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

注意:虽然设置了忽略C,但它还是参与排名的,因此结果中只有1,3,没有2。

如果两个向量元素相同但顺序不同,如何重排

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"

既然涉及到排序那就再说一下rank,order,sort
其实刚才的例子可以直接sort(y)解决。

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的返回值意为:原向量中的第1个元素排第3名,第2个元素排第1名,以此类推。
order的返回值意为:最小值在第2位,次小值在第3位。。。最大值在第4位
sort则比较简单,从小到大派了个序。
rev是将向量中的元素从后到前输出。

更直观的看一下,以刚才的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"

转载于:https://www.jianshu.com/p/fba990bde546

猜你喜欢

转载自blog.csdn.net/weixin_33850890/article/details/91071337
rev
今日推荐