我有一个很大的稀疏矩阵,并且想逐列排列它的非零元素。我现在使用的方法是将所有零转换为NA。这种方法的问题是,矩阵不再是稀疏的,并且在这样做时具有空间复杂性。
是否有任何方法使用函数rank而不将零转换为NA?可复制的例子:
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)})我想要一个相同大小的稀疏矩阵,用列级代替非零值。
发布于 2017-01-20 22:00:37
你的例子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我想要一个相同大小的稀疏矩阵,用列级代替非零值。
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 1https://stackoverflow.com/questions/41772943
复制相似问题