获取矩阵条目的排名? [英] Get rank of matrix entries?
问题描述
假设一个矩阵:
> a <- matrix(c(100, 90, 80, 20), 2, 2)
> a
[,1] [,2]
[1,] 100 80
[2,] 90 20
假设我想将矩阵的元素转换为秩:
Suppose I want to convert the elements of the matrix to ranks:
>rank.a <- rank(a)
> rank.a
[1] 4 3 2 1
这将返回一个向量,即矩阵结构丢失.是否可以对矩阵进行排序,以使输出形式为:
This returns a vector, i.e. the matrix structure is lost. Is it possible to rank a matrix such that the output will be of the form:
[,1] [,2]
[1,] 4 2
[2,] 3 1
推荐答案
@EDi答案的另一种方法是复制a
,然后将rank(a)
的输出直接分配到a
副本的元素中:
An alternative to @EDi's Answer is to copy a
and then assign the output of rank(a)
directly into the elements of the copy of a
:
> a <- matrix(c(100, 90, 80, 20), 2, 2)
> rank.a <- a
> rank.a[] <- rank(a)
> rank.a
[,1] [,2]
[1,] 4 2
[2,] 3 1
通过查询输入矩阵的尺寸,可以避免重建矩阵.
That saves you from rebuilding a matrix by interrogating the dimensions of the input matrix.
请注意(如@Andrie在评论中所述),仅当要保留原始a
时才需要复制a
.需要注意的主要点是,由于a
已经具有适当的尺寸,因此我们可以将其视为向量,并用a
等级的向量替换a
的内容.
Note that (as @Andrie mentions in the comments) the copying of a
is only required if one wants to keep the original a
. The main point to note is that because a
is already of the appropriate dimensions, we can treat it like a vector and replace the contents of a
with the vector of ranks of a
.
这篇关于获取矩阵条目的排名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!