YevgenyM
YevgenyM

Reputation: 91

R: Convert COO format matrix to regular matrix format

I have a square matrix in a COO (Coordinate list) format.

For example:

From  To   Value
1     1     1
1     2     1
2     1     0
2     2     1

I want to convert it into regular R matrix format. So it will look like this:

      [,1] [,2]
[1,]   1    1
[2,]   0    1

Please advise how to do it.

Upvotes: 0

Views: 242

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

You can do this with xtabs in base R, like this:

out <- xtabs(coo_mat[, 3] ~ coo_mat[, 1] + coo_mat[, 2])
out
#             coo_mat[, 2]
# coo_mat[, 1] 1 2
#            1 1 1
#            2 0 1

The result is an object of classes "xtabs" and "table".

class(out)
# [1] "xtabs" "table"

If you want to get rid of the dimnames and the other attributes, you can do the following:

`dim<-`(`attributes<-`(out, NULL), dim(out))
#      [,1] [,2]
# [1,]    1    1
# [2,]    0    1

Upvotes: 0

YevgenyM
YevgenyM

Reputation: 91

Here is a way I found:

Using Matrix package.

First, the table from the example:

> coo_mat <- rbind(c(1,1,1), c(1,2,1), c(2,1,0), c(2,2,1))
> coo_mat
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    2    1
[3,]    2    1    0
[4,]    2    2    1

Now, make it regular format matrix:

> as.matrix(Matrix::sparseMatrix(i=coo_mat[,1], j=coo_mat[,2], x=coo_mat[,3]))

     [,1] [,2]
[1,]    1    1
[2,]    0    1

Upvotes: 1

Related Questions