How to change a matrix into a triple in R (row, col, value)

Search on bing:

How to change the matrix to triple form and search the result on bing:

All kinds of C language can't find the way to realize R language

R language writing cycle is very slow, just use the ready-made package

Matrix

Matrix is a very powerful package. It can convert matrix to sparse matrix, change 0 to... And save resources

Test, generate a matrix of 10 * 10, which contains a large number of zeros. Now convert the non-zero parts into the form of triples

What is a triple? Even if the matrix is transformed into the form of three columns, the original matrix is two-dimensional, now extract its row number as the first column, extract its column number as the second column, extract the corresponding value as the third column

For example:

1 2
3 4

To triple is:

1 1 1
1 2 2
2 1 3
2 2 4

test data

# Matrix into triple form: R language matrix
mm = matrix(sample(c(0,0,2),size = 100,replace = T),10,10)
# Let's say it's a symmetric matrix, only the lower triangle is preserved, so the upper triangle is 0
mm[upper.tri(mm)] = 0
mm
> mm
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    2    0    0    0    0    0    0    0    0     0
 [2,]    0    2    0    0    0    0    0    0    0     0
 [3,]    0    2    2    0    0    0    0    0    0     0
 [4,]    0    0    0    0    0    0    0    0    0     0
 [5,]    0    0    0    0    2    0    0    0    0     0
 [6,]    0    0    0    2    2    0    0    0    0     0
 [7,]    0    0    0    0    0    0    0    0    0     0
 [8,]    2    0    0    0    2    0    0    0    0     0
 [9,]    0    0    0    2    0    2    0    0    0     0
[10,]    0    0    0    0    0    0    0    2    2     0

Convert to sparse matrix:

As you can see, all zeros of a sparse matrix become dots

library(Matrix)
smm = Matrix(mm)
smm
> smm
10 x 10 sparse Matrix of class "dtCMatrix"
                         
 [1,] 2 . . . . . . . . .
 [2,] . 2 . . . . . . . .
 [3,] . 2 2 . . . . . . .
 [4,] . . . . . . . . . .
 [5,] . . . . 2 . . . . .
 [6,] . . . 2 2 . . . . .
 [7,] . . . . . . . . . .
 [8,] 2 . . . 2 . . . . .
 [9,] . . . 2 . 2 . . . .
[10,] . . . . . . . 2 2 .

Convert sparse matrix to triple

# Change to triples
re = summary(smm)
sm = as.data.frame(re)
sm

Result:

> sm
    i j x
1   1 1 2
2   8 1 2
3   2 2 2
4   3 2 2
5   3 3 2
6   6 4 2
7   9 4 2
8   5 5 2
9   6 5 2
10  8 5 2
11  9 6 2
12 10 8 2
13 10 9 2

This should be a more efficient method

Full code:

# Matrix into triple form: R language matrix
mm = matrix(sample(c(0,0,2),size = 100,replace = T),10,10)
mm

# Let's say it's a symmetric matrix, only the lower triangle is preserved, so the upper triangle is 0
mm[upper.tri(mm)] = 0
mm

library(Matrix)
smm = Matrix(mm)
smm

# Change to triples
re = summary(smm)
sm = as.data.frame(re)
sm
library(dplyr)
arrange(sm,i,j)

Keywords: R Language C

Added by ph0ngwh0ng on Tue, 26 Nov 2019 22:02:06 +0200