0

如何转换矩阵

A 1 2 3
B 3 6 9
c 5 6 9
D 1 2 4

变成如下形式:

   1 2 3 4 5 6 7 8 9
1  0 2 1 1 0 0 0 0 0
2  0 0 1 1 0 0 0 0 0  
3  0 0 0 0 0 1 0 0 1    
4  0 0 0 0 0 0 0 0 0      
5  0 0 0 0 0 1 0 0 1           
6  0 0 0 0 0 0 0 0 2         
7  0 0 0 0 0 0 0 0 0           
8  0 0 0 0 0 0 0 0 0               
9  0 0 0 0 0 0 0 0 0               

我有一些实现,但它使用 for 循环我想知道 R 中是否有一些内部函数(例如“应用”)

补充:抱歉混淆。第一个矩阵只是表示项目集,每组项目成对出现,例如第一组是“1 2 3”,将变为(1,2),(1,3), (2,3),对应第二个矩阵。

还有另一个问题:如果矩阵非常大(10000000*10000000)并且是稀疏的,我应该使用稀疏矩阵还是 big.matrix?

谢谢!

4

1 回答 1

3

从 M 中删除行名给出:

m <- matrix(c(1,3,5,1,2,6,6,2,3,9,9,4), nrow=4)

> m
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    3    6    9
## [3,]    5    6    9
## [4,]    1    2    4

# The indicies that you want to increment in x, but some are repeated
# combn() is used to compute the combinations of columns
indices <- matrix(t(m[,combn(1:3,2)]),,2,byrow=TRUE)

# Count repeated rows
ones <- rep(1,nrow(indices))
cnt <-  aggregate(ones, by=as.data.frame(indices), FUN=sum)

# Set each value to the appropriate count
x <- matrix(0, 9, 9)
x[as.matrix(cnt[,1:2])] <- cnt[,3]

x

##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
##  [1,]    0    2    1    1    0    0    0    0    0
##  [2,]    0    0    1    1    0    0    0    0    0
##  [3,]    0    0    0    0    0    1    0    0    1
##  [4,]    0    0    0    0    0    0    0    0    0
##  [5,]    0    0    0    0    0    1    0    0    1
##  [6,]    0    0    0    0    0    0    0    0    2
##  [7,]    0    0    0    0    0    0    0    0    0
##  [8,]    0    0    0    0    0    0    0    0    0
##  [9,]    0    0    0    0    0    0    0    0    0
于 2013-03-28T04:00:21.580 回答