2014-12-05 290 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