0

I need to extract the row of sparseMatrix as sparseVector, however 'drop=FALSE' option does not work well for me.

To explain the issue, I will use an example from extract sparse rows from sparse matrix in r (my question is different since I need to convert extracted row to vector):

i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)
A <- sparseMatrix(i, j, x = x)
b <- sparseVector(7,2,10)

now A[1,,drop=FALSE] and b should have the same value.

However, A[1,,drop=FALSE] is still a matrix with 2 dimensions. So if I try Matrix::crossprod(b), I get:

1 x 1 Matrix of class "dsyMatrix"
     [,1]
[1,]   49

but if I try Matrix::crossprod(A[1,,drop=FALSE]), then I get:

10 x 10 sparse Matrix of class "dsCMatrix"

[1,] .  . . . . . . . . .
[2,] . 49 . . . . . . . .
[3,] .  . . . . . . . . .
[4,] .  . . . . . . . . .
[5,] .  . . . . . . . . .
[6,] .  . . . . . . . . .
[7,] .  . . . . . . . . .
[8,] .  . . . . . . . . .
[9,] .  . . . . . . . . .
[10,] .  . . . . . . . . .

How can I get just 49 in the second case in efficient way (Matrix::crossprod should be faster than %*%, as far as I understand from the description of the function)?

Also, b%*%b works perfectly correct, while A[1,,drop=FALSE]%*%A[1,,drop=FALSE] returns the following error:

Cholmod error 'A and B inner dimensions must match' at file ../MatrixOps/cholmod_ssmult.c, line 82
Community
  • 1
  • 1
Andrey Sapegin
  • 454
  • 8
  • 33

1 Answers1

1

I am not quite sure there is a method for (directly) casting a sparse matrix row as a sparse vector.

The reason why you are getting an error from

A[1,,drop=FALSE]%*%A[1,,drop=FALSE]

is that you're multiplying matrices that have the same dimension. You need to transpose the second matrix:

A[1,,drop=FALSE] %*% t(A[1,,drop=FALSE])

will return a 1x1 sparse matrix which you can then cast as.numeric()

BjaRule
  • 171
  • 5