我有一个COO (Coordinate list)格式的方阵。R:将COO格式矩阵转换为常规矩阵格式
例如:
From To Value
1 1 1
1 2 1
2 1 0
2 2 1
我想把它转换成普通R矩阵格式。 所以它看起来是这样的:
[,1] [,2]
[1,] 1 1
[2,] 0 1
请告诉如何去做。
我有一个COO (Coordinate list)格式的方阵。R:将COO格式矩阵转换为常规矩阵格式
例如:
From To Value
1 1 1
1 2 1
2 1 0
2 2 1
我想把它转换成普通R矩阵格式。 所以它看起来是这样的:
[,1] [,2]
[1,] 1 1
[2,] 0 1
请告诉如何去做。
这是一种方法,我发现:
使用Matrix包。
首先,从示例表:
> 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
现在,使其常规格式矩阵:
> as.matrix(Matrix::sparseMatrix(i=coo_mat[,1], j=coo_mat[,2], x=coo_mat[,3]))
[,1] [,2]
[1,] 1 1
[2,] 0 1
您可以在基础R与xtabs
做到这一点,是这样的:
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
结果是类“xtabs”和“table”的对象。
class(out)
# [1] "xtabs" "table"
如果你想摆脱dimnames
和其他attributes
的,你可以做到以下几点:
`dim<-`(`attributes<-`(out, NULL), dim(out))
# [,1] [,2]
# [1,] 1 1
# [2,] 0 1