2014-12-05 288 views

回答

0

這是一種方法,我發現:

使用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 
0

您可以在基礎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