Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

r - How to convert a sparse matrix into a matrix of index and value of non-zero element

We can construct a sparse matrix from an index and value of non-zero element with the sparseMatrix or spMatrix. Is there any function convert a sparse matrix back to an index and value of all non-zero element? For example

i <- c(1,3,5); j <- c(1,3,4); x <- 1:3
A <- sparseMatrix(i, j, x = x)

B <- sparseToVector(A)
## test case:
identical(B,cbind(i,j,x))

Is there any function do a similar job as sparseToVector?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your matrix A is in the sparse compressed Format (class dgCMatrix). You can coerce it into the non-compressed sparse format by

A.nc <- as (A, "dgTMatrix")

Or, you could have specified giveCsparse = TRUE in the sparseMatrix call.

The triplet form of dgTMatrix basically contains all you're looking for in slots i, j, and x, just i and j indexing is done with 0-based offsets:

> str (A.nc)
Formal class 'dgTMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3] 0 2 4
  ..@ j       : int [1:3] 0 2 3
  ..@ Dim     : int [1:2] 5 4
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:3] 1 2 3
  ..@ factors : list()

> cbind (i = A.nc@i + 1, j = A.nc@j + 1, x = A.nc@x)
     i j x
[1,] 1 1 1
[2,] 3 3 2
[3,] 5 4 3
> all (cbind (i = A.nc@i + 1, j = A.nc@j + 1, x = A.nc@x) == cbind (i, j, x))
[1] TRUE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...