1

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

user3714759
  • 11
  • 1
  • 2

1 Answers1

4

You can use drop = FALSE:

A[1, , drop = FALSE]
# 1 x 10 sparse Matrix of class "dgCMatrix"
#                        
# [1,] . 7 . . . . . . . .
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Thank you for your suggestion. May I ask you another question? When I got the row, x = A[1, , drop = FALSE], I need to perform its outer product p = x %o% x, but p is still a dense matrix... Is there any command to set the "sparse environment" in R? – user3714759 Jun 06 '14 at 13:40
  • @user3714759 You can try `library(Matrix); Matrix(x %o% x, sparse = TRUE)`. The `"%o%"` function returns a "normal" matrix. – Sven Hohenstein Jun 06 '14 at 14:02