在稀疏矩阵中逐列排列非零元素
Rank non zeros elements column by column in a sparse matrix
我有一个很大的稀疏矩阵,想按列对其非零元素进行排序。我现在使用的方法是将所有零转换为NA
。这种方法的问题是,矩阵不再稀疏,并且在这样做时具有 space 复杂性。
有没有什么方法可以在不将零转换为 NA
的情况下使用函数 rank
?可重现的例子:
library(Matrix)
TestMatrix = Matrix(c(0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11), 5, sparse = TRUE)
TestMatrix = replace(TestMatrix, TestMatrix == 0, NA)
apply(-TestMatrix, 2, function(x) {rank(x, na.last = TRUE)})
我想要一个相同大小的稀疏矩阵,其中非零值替换为按列排序。
你的例子TestMatrix
:
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] . . . . .
#[2,] 100 100 100 100 100
#[3,] 12 12 12 12 12
#[4,] . . . . .
#[5,] 11 11 11 11 11
I want a sparse matrix of the same size, with non-zero values replaced by column-wise rank.
n <- diff(TestMatrix@p) ## number of non-zeros per column
lst <- split(TestMatrix@x, rep.int(1:ncol(TestMatrix), n)) ## columns to list
r <- unlist(lapply(lst, rank)) ## column-wise ranking and result collapsing
RankMatrix <- TestMatrix ## copy sparse matrix
RankMatrix@x <- r ## replace non-zero elements with rank
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] . . . . .
#[2,] 3 3 3 3 3
#[3,] 2 2 2 2 2
#[4,] . . . . .
#[5,] 1 1 1 1 1
我有一个很大的稀疏矩阵,想按列对其非零元素进行排序。我现在使用的方法是将所有零转换为NA
。这种方法的问题是,矩阵不再稀疏,并且在这样做时具有 space 复杂性。
有没有什么方法可以在不将零转换为 NA
的情况下使用函数 rank
?可重现的例子:
library(Matrix)
TestMatrix = Matrix(c(0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11,
0,100,12,0,11), 5, sparse = TRUE)
TestMatrix = replace(TestMatrix, TestMatrix == 0, NA)
apply(-TestMatrix, 2, function(x) {rank(x, na.last = TRUE)})
我想要一个相同大小的稀疏矩阵,其中非零值替换为按列排序。
你的例子TestMatrix
:
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] . . . . .
#[2,] 100 100 100 100 100
#[3,] 12 12 12 12 12
#[4,] . . . . .
#[5,] 11 11 11 11 11
I want a sparse matrix of the same size, with non-zero values replaced by column-wise rank.
n <- diff(TestMatrix@p) ## number of non-zeros per column
lst <- split(TestMatrix@x, rep.int(1:ncol(TestMatrix), n)) ## columns to list
r <- unlist(lapply(lst, rank)) ## column-wise ranking and result collapsing
RankMatrix <- TestMatrix ## copy sparse matrix
RankMatrix@x <- r ## replace non-zero elements with rank
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] . . . . .
#[2,] 3 3 3 3 3
#[3,] 2 2 2 2 2
#[4,] . . . . .
#[5,] 1 1 1 1 1