I can define a sparse Matrix using a vector for i, j, and x:
i <- c(1,3:8)
j <- c(2,9,6:10)
x <- 7 * (1:7)
(A <- sparseMatrix(i, j, x = x))
I want to extract the i
, j
, and x
elements from this sparse matrix, so I can re-create the matrix in another package. This is easy with i
and x
:
i <- A@i + 1
x <- A@x
(Note that the order of i and x has changed, but their relative association is the same: i=4 is still in the same place as x=21)
However, the last element of the sparse matrix is p
: "a numeric (integer valued) vector of pointers, one for each column (or row), to the initial (zero-based) index of elements in the column (or row)."
How can I convert A@i
and A@p
into the original j
element used to define the matrix?
It is a little tricky to figure out how columns is stored. I have a hard time explaining it, but maybe the code will help you get what is going on:
# Rows
A@i+1
# [1] 1 4 5 6 3 7 8
# Cols (a little tricky..)
findInterval(seq(A@x)-1,A@p[-1])+1
# [1] 2 6 7 8 9 9 10
# Values
A@x
# [1] 7 21 28 35 14 42 49
So, after you remove the first element, A@p
has one element for every column. The range of A@p+1
is 1:length(A@x)
. Basically, for each column, it says that the first element of A@x
that occurs in this column is located at this index of A@x
. But the tricky part is that if nothing is located in that column, then it uses the index of the last column. That is my bad explanation... hopefully it will help in conjunction with the code.
Much easier with a TsparseMatrix object:
A <- as(A, "TsparseMatrix")
8 x 10 sparse Matrix of class "dgTMatrix"
[1,] . 7 . . . . . . . .
[2,] . . . . . . . . . .
[3,] . . . . . . . . 14 .
[4,] . . . . . 21 . . . .
[5,] . . . . . . 28 . . .
[6,] . . . . . . . 35 . .
[7,] . . . . . . . . 42 .
[8,] . . . . . . . . . 49
> dput(A)
new("dgTMatrix"
, i = c(0L, 3L, 4L, 5L, 2L, 6L, 7L)
, j = c(1L, 5L, 6L, 7L, 8L, 8L, 9L)
, Dim = c(8L, 10L)
, Dimnames = list(NULL, NULL)
, x = c(7, 21, 28, 35, 14, 42, 49)
, factors = list()
)
Can also create but need to specify dimensions:
(A <- spMatrix(8,10, i=i, j=j, x = x))