extract sparse rows from sparse matrix in r

不羁岁月 提交于 2019-12-11 11:43:55

问题


I have a large sparse matrix to analyze in R. For instance:

i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)
(A <- sparseMatrix(i, j, x = x))
[1,] . 7 . . .  .  .  .  .  .
[2,] . . . . .  .  .  .  .  .
[3,] . . . . .  .  .  . 14  .
[4,] . . . . . 21  .  .  .  .
[5,] . . . . .  . 28  .  .  .
[6,] . . . . .  .  . 35  .  .
[7,] . . . . .  .  .  . 42  .
[8,] . . . . .  .  .  .  . 49

I want to extract the i-th row from this matrix, as a sparse vector. If I write

(x=A[1,])

I obtain

 [1] 0 7 0 0 0 0 0 0 0 0

but what I would like is

 [1] . 7 . . . . . . . .

What I expect is that the new vector does not materialize the zeros. How can I do this?

Thanks


回答1:


You can use drop = FALSE:

A[1, , drop = FALSE]
# 1 x 10 sparse Matrix of class "dgCMatrix"
#                        
# [1,] . 7 . . . . . . . .


来源:https://stackoverflow.com/questions/24080614/extract-sparse-rows-from-sparse-matrix-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!