dgtmatrix .mtx_cols in r

To manipulate and work with dgtmatrix objects in R, you can use the Matrix package. First, you need to install and load the package:

main.r
install.packages("Matrix")
library(Matrix)
43 chars
3 lines

To create a dgtmatrix object, you can use the Diagonal() function:

main.r
# create dgtmatrix
mat <- Diagonal(1:4, 1:4, dims = 4)
mat

4 x 4 sparse Matrix of class "dgTMatrix"
          
[1,] 1 . . .
[2,] . 2 . .
[3,] . . 3 .
[4,] . . . 4
164 chars
11 lines

To access the columns of the dgtmatrix, you can use the mtx_cols() function:

main.r
# access columns
cols <- mtx_cols(mat)
cols

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4
96 chars
16 lines

The mtx_cols() function returns a list of the column indices of the non-zero elements in the dgtmatrix. In this case, it returns a list of 4 elements, each containing a single integer corresponding to the column index of the non-zero element in that column.

You can also access the values of the columns using the $ operator on the dgtmatrix object:

main.r
# access column values
mat$values[cols[[1]]]

[1] 1

mat$values[cols[[2]]]

[1] 2

mat$values[cols[[3]]]

[1] 3

mat$values[cols[[4]]]

[1] 4
142 chars
17 lines

This will return the non-zero elements in each column of the dgtmatrix object.

gistlibby LogSnag