R语言rank函数详细解析

    xiaoxiao2021-03-25  308

    前言:在R中,和排序相关的函数主要有三个:sort(),rank(),order()。  sort(x)是对向量x进行排序,返回值排序后的数值向量。rank()是求秩的函数,它的返回值是这个向量中对应元素的“排名”。而order()的返回值是对应“排名”的元素所在向量中的位置。 

    下面以一小段R代码来举例说明:

    > x<-c(97,93,85,74,32,100,99,67) > sort(x) [1] 32 67 74 85 93 97 99 100 > order(x) [1] 5 8 4 3 2 1 7 6 > rank(x) [1] 6 5 4 3 1 8 7 2

    1.rank函数是什么

    rank相关文档[1]可以译为"返回原数组(?)中各个元素排序(?)后的秩次(?)",表面上看确实可以得到次序,但对数组、排序、秩次交待不清。

    2.rank函数使用情景

    比如,在100米赛跑中,甲乙丙三人的成绩为6.8s, 8.1s, 7.2s,那么用rank函数排序获得名次:

    > rank(t <- c(6.8, 8.1, 7.2)) [1] 1 3 2

    再如,甲乙丙三人考试得分为74,92,85,用同样方法取得名次会适得其反。当然,我们可以认为执行

    > rank(-(s <- c(74, 92, 85))) [1] 3 1 2

    可以达到目的,但这并未改变rank函数的排序机制。

    3.rank函数排序类型

    rank(x, na.last = TRUE,      ties.method = c("average", "first", "random", "max", "min"))

    > t <- c(4, NaN, 4, 7, 8, 2, NaN, 9, 9, 7, NaN, 5, 2, 2, 1) #同时对相应元素做好标记 > names(t) <- letters[1 : length(t)]

    通过以上方法进行排序,得出

    Result   a b c d e f g h i j k l m n o original 4 NaN 4 7 8 2 NaN 9 9 7 NaN 5 2 2 1 average 5.5 13.0 5.5 8.5 10.0 3.0 14.0 11.5 11.5 8.5 15.0 7.0 3.0 3.0 1.0 first 5 13 6 8 10 2 14 11 12 9 15 7 3 4 1 random (1) 6 13 5 9 10 2 14 11 12 8 15 7 3 4 1 random (2) 5 13 6 8 10 2 14 11 12 9 15 7 4 3 1 max 6 13 6 9 10 4 14 12 12 9 15 7 4 4 1 min 5 13 5 8 10 2 14 11 11 8 15 7 2 2 1

    我们发现,标签"b","g","k"的次序并未发生改变,可推断ties.method作用在于处理非缺失值的顺序。

    不妨参考rank的实现代码

    function (x, na.last = TRUE, ties.method = c("average", "first", "random", "max", "min")) { nas <- is.na(x) #得到与x相同长度的boolean型数组,用来标记相应位是否为缺失值 nm <- names(x) #获取数组中元素所对应的标签   #names函数暗示了该方法的设计初衷是对一维数组即列向量进行排序,虽然x为矩阵也会得出结果,但nm的作用已经失效,结果不具有意义    ties.method <- match.arg(ties.method) if (is.factor(x)) x <- as.integer(x) #若x为因子,则对元素"归类",并按"类的大小"进行整数元素编码,具体请见[说明1] x <- x[!nas] #剔除x中的缺失值   #average\min\max采用了相应的.Internal(rank(x, length(x), ties.method)),具体请见[说明2]   #first采用了sort.list(sort.list(x)),具体请见[说明3]   #random采用了sort.list(order(x, stats::runif(sum(!nas)))),具体请见[说明4] y <- switch(ties.method, average = , min = , max = .Internal(rank(x, length(x), ties.method)), first = sort.list(sort.list(x)), random = sort.list(order(x, stats::runif(sum(!nas)))))   #下面是补全缺失值的次序的方法   #na.last = "keep",不处理缺失值,na.last = TRUE,后排序缺失值,na.last = FALSE,先排序缺失值。 if (!is.na(na.last) && any(nas)) { yy <- NA NAkeep <- (na.last == "keep") if (NAkeep || na.last) { yy[!nas] <- y if (!NAkeep) yy[nas] <- (length(y) + 1L):length(yy) } else { len <- sum(nas) yy[!nas] <- y + len yy[nas] <- seq_len(len) } y <- yy names(y) <- nm } else names(y) <- nm[!nas] y }

    [说明1] 关于因子转整数

    > f <- c('Ba', 'BA', 'b', 'A', 'A', 'b', 'Ba', 'Bac', NaN, NaN) > fac <- factor(colour) > as.integer(fac) [1] 3 4 2 1 1 2 3 5 6 6

    由此可见: (1) 因子会作为字符串进行机械比较,排出次序。(2) 因子中任意两个缺失值地位(大小)相同。

    实际问题中,因子为人为设定,故采用有序因子(ordered factor),消除机械转换的干扰。

    > qulity <- c('good','soso','good','soso','bad','good','bad') > names(qulity) <- c('day1','day2','day3','day4','day5','day6','day7') > q <- factor(qulity, levels = c('bad','soso','good'), labels = c('bad', 'soso', 'good'), order = TRUE) > rank(q) day1 day2 day3 day4 day5 day6 day7 6.0 3.5 6.0 3.5 1.5 6.0 1.5

    [说明2] "average", "max", "min" 排序

    > t a b c d e f g h i j k l m n o 4 NaN 4 7 8 2 NaN 9 9 7 NaN 5 2 2 1 > rank(t, na.last = "keep", ties.method = "first") a b c d e f g h i j k l m n o 5 NA 6 8 10 2 NA 11 12 9 NA 7 3 4 1 > rank(t, na.last = "keep", ties.method = "average") a b c d e f g h i j k l m n o 5.5 NA 5.5 8.5 10.0 3.0 NA 11.5 11.5 8.5 NA 7.0 3.0 3.0 1.0

    可以将"average"排序理解为先对数据进行"first"排序,即全部元素都有唯一且不同的次序。

    如f, m, n 得分相同,但可按先后次序排成2, 3, 4, 但是f, m, n属于同一群体,故可以取该群体中的平均水平作为次序,使得分相同的元素地位相当。

    故不难理解"max"排序是群体中的元素全部取群中最好的水平,这也是普遍采用的“并列排名”方法;

    "min"排序是群体中的元素全部取群体中最差的水平,这样增大了不同等级的顺序差异。

     [说明3] first = sort.list(sort.list(x))

    对序列先按大小排序,大小相同的元素,从头至尾由小到大排序。

    > x a c d e f h i j l m n o 4 4 7 8 2 9 9 7 5 2 2 1 > sort.list(sort.list(x)) [1] 5 6 8 10 2 11 12 9 7 3 4 1

    [说明4] random = sort.list(order(x, stats::runif(sum(!nas))))

    weight = stats::runif(sum(!nas)) 为每个已知元素生成0-1之间随机数,作为“权重”序列weight

    sort.list(order(x, weigth)) 依据随机的“权重”决定得分相同的元素的次序

    不妨人为参与权重设计

    a c d e f h i j l m n o 4 4 7 8 2 9 9 7 5 2 2 1 > weight = c(0.45, 0.55, 0.1, 0.1, 0.1, 0.55, 0.45, 0.1, 0.1, 0.3, 0.1, 0.1); > sort.list(order(x,weight)) [1] 5 6 8 10 2 12 11 9 7 4 3 1

    不难发现,a, c 得分均为4,但w(a) = 0.45 < w(c) = 0.55, 遵照小号在前,a 排在c 前面。h, j 刚好相反w(h) = 0.55 > w(j) = 0.45, j 排在h 前面。

    d, j 得分,“权重”均相同,故按之前从头到尾递增顺序排列。

    f, m, n 得分均为2, w(f) = w(n) = 0.1 < w(m) = 0.3, 排序结果为f < n < m, 由此可见,“权重”优先于“前后顺序”,这样做使得排序更加随机化,若序列存在大量得分相同的元素,一定程度克服了“前小后大”规则的约束,使排序结果更随机。

    以上仅为说明随机排序的机制,实际应用中只能确定小数在前大数在后,并不能解释相同的数之间的顺序。

    4.rank函数小结

    rank(x, na.last = TRUE,      ties.method = c("average", "first", "random", "max", "min"))

    (1) rank 函数是对一维度数组、向量x 进行排序。若x 为数值,则按照小数在线大数在后的原则进行排序,若x 为因子,则应参考[说明1]进行顺序因子设计。

    P.S. 实际情况中,存在大量用二维表格描述的数据,比如行表示地点列表示时间的统计表,若进行排序,应先通过字符拼接的手段将表格转化为一维的向量,否则结果将失去意义。

    (2) rank 将数据分为确定值与缺失值两种。缺失值可按先后排在确定值之间(na.last = FALSE), 也可排在之后(na.last = TRUE), 也可保留,不参与排序(na.last = "keep").

    (3) "first" 是最基本的排序,小数在前大数在后,相同元素先者在前后者在后。

      "max" 是相同元素都取该组中最好的水平,即通常所讲的并列排序。

      "min" 是相同元素都取该组中最差的水平,可以增大序列的等级差异。

      "average" 是相同元素都取该组中的平均水平,该水平可能是个小数。

      "random" 是相同元素随机编排次序,避免了“先到先得”,“权重”优于“先后顺序”的机制增大了随机的程度。

    [1]Returns the sample ranks of the values in a vector. Ties (i.e., equal values) and missing values can be handled in several ways.

    order(X, na.last=TRUE, decreasing=FALSE)

    返回值: X排好序的下标向量 na.last 控制空值NA排在最前还是最后,默认最后 desceasing 控制升序还是降序排列 例子: > #vector > X <- c(7,4,5,2,8,1,9,3) > order(X) [1] 6 4 8 2 3 1 5 7 > X[order(X)] [1] 1 2 3 4 5 7 8 9> X[order(X, decreasing=TRUE)] [1] 9 8 7 5 4 3 2 1 > order(-X) # '-' equals decreasing=TRUE[1] 7 5 1 3 2 4 8 6 > #vector > #dataframe. > X <- c(7,4,5,3,8,1,9,3) > Y <- c(50, 80, 30, 70, 20, 10, 40, 90) > order(X, Y) #only print X's order, no Y's [1] 6 4 8 2 3 1 5 7 > table_1 <- data.frame(x=X, y=Y) > table_1 x y 1 7 50 2 4 80 3 5 30 4 3 70 5 8 20 6 1 10 7 9 40 8 3 90> order(table_1$x, table_1$y) #X asc, Y asc, print the row number's sequence [1] 6 4 8 2 3 1 5 7> table_1[order(table_1$x, -table_1$y),] #X asc, Y desc x y 6 1 10 8 3 904 3 70 2 4 80 3 5 30 1 7 50 5 8 20 7 9 40 > table_1[order(-table_1$x, table_1$y), ] #X desc, Y asc x y 7 9 40 5 8 20 1 7 50 3 5 30 2 4 80 4 3 70 8 3 90 6 1 10 > table_1[order(-table_1$x, -table_1$y), ] #X desc, Y desc x y 7 9 40 5 8 20 1 7 50 3 5 30 2 4 80 8 3 90 4 3 70 6 1 10

    转载请注明原文地址: https://ju.6miu.com/read-5410.html

    最新回复(0)