Search code examples
rsparse-matrix

Create vector p for a sparse Matrix from a matrix of positions


Let's say I want to create a sparse matrix SMatrix where all non-zero values are 1. I already have a matrix of positions, where column 1 stores row index and column 2 stores col index:

vec1 <- c(10,1)
vec2 <- c(12,1)
vec3 <- c(2,3)

positions <- matrix(c(vec1, vec2, vec3),
                    ncol=2,
                    dimnames = list(NULL, c("row", "col")),
                    byrow = T)
positions
     row col
[1,]  10   1
[2,]  12   1
[3,]   2   3

I can create the vector x and i which will be the equivalent of SMatrix@x and SMatrix@i like this:

x <- rep(1, nrow(positions))
i <- positions[order(positions[,2]),1] - 1

But how can I create the vector p, which should be the equivalent of SMatrix@p ?


Solution

  • You can use Matrix::sparseMatrix to get the compressed, or pointer representation of the row or column indices.

    Matrix::sparseMatrix(positions[,1], positions[,2], x=1)@p
    #[1] 0 2 2 3
    

    or use diffinv like:

    diffinv(c(table(factor(positions[,2], seq_len(max(positions[,2]))))))
    #[1] 0 2 2 3
    

    Doing the opposite of:

    dp <- diff(p)
    rep(seq_along(dp),dp)
    

    What is given in the manual to expanded form p to row or column indices.