获取矩阵条目的排名?
假设一个矩阵:
> a <- matrix(c(100, 90, 80, 20), 2, 2)
> a
[,1] [,2]
[1,] 100 80
[2,] 90 20
假设我想将矩阵的元素转换为行列:
>rank.a <- rank(a)
> rank.a
[1] 4 3 2 1
这将返回一个向量,即矩阵结构丢失。是否可以对矩阵进行排序,使得输出的形式为:
[,1] [,2]
[1,] 4 2
[2,] 3 1
Assume a matrix:
> 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@EDi 的答案的另一种选择是复制
a
,然后将rank(a)
的输出直接分配到a
副本的元素中:这样您就不必通过询问输入矩阵的维度来重建矩阵。
请注意(正如 @Andrie 在评论中提到的)只有在想要保留原始
a
时才需要复制a
。需要注意的要点是,由于a
已经具有适当的维度,因此我们可以将其视为向量,并将a
的内容替换为a
的秩向量代码>a。An alternative to @EDi's Answer is to copy
a
and then assign the output ofrank(a)
directly into the elements of the copy ofa
:That saves you from rebuilding a matrix by interrogating the dimensions of the input matrix.
Note that (as @Andrie mentions in the comments) the copying of
a
is only required if one wants to keep the originala
. The main point to note is that becausea
is already of the appropriate dimensions, we can treat it like a vector and replace the contents ofa
with the vector of ranks ofa
.为什么不将向量转换回矩阵,其尺寸与原始矩阵相同?
why not convert the vector back to a matrix, with the dimensions of the original matrix?
@Gavin Simpson 有一个非常好的和优雅的解决方案!但有一个警告:
矩阵的类型将保持不变或扩大。大多数情况下您不会注意到,但请考虑以下事项:
由于矩阵一开始就是字符,因此
rank
值(双精度)被强制转换为字符串!这是一种更安全的方法,只需复制所有属性:
或者,作为单行使用
struct
仅复制相关属性(但需要更多输入):当然,
dimnames
在这种特殊情况下可以被忽略。@Gavin Simpson has a very nice and elegant solution! But there is one caveat though:
The type of the matrix will stay the same or be widened. Mostly you wouldn't notice, but consider the following:
Since the matrix was character to start with, the
rank
values (which are doubles) got coerced into character strings!Here's a safer way that simply copies all the attributes:
Or, as a one-liner using
structure
to copy only the relevant attributes (but more typing):Of course,
dimnames
could be left out in this particular case.