2013-03-28 47 views
0

如何變換像如何改造一個項目設置的矩陣R中

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    

我有一些實施,但它使用的循環 我想知道R裏面是否有一些內在的功能(例如「申請」)

加: 對不起,我很困惑。第一個矩陣只是表示項目集合,例如第一組是「1 2 3」,並且將變成(1,2),(1,3),(2,3),對應於第二個矩陣。

和另一個問題: 如果矩陣非常大(10000000 * 10000000)並且是稀疏 應該使用稀疏矩陣還是big.matrix?

謝謝!

+1

如何在您的兩個矩陣有關嗎?你的第一個矩陣是什麼意思? – mnel 2013-03-28 03:04:02

+0

對不起。第一個矩陣只是表示項目集合,每一組項目出來對,例如第一個集合是「1 2 3」,並且將變成(1,2),(1,3),( 2,3)對應第二個矩陣。 – heyflypig 2013-03-28 03:49:53

+0

@heyflypig歡迎來到SO。很酷的問題!希望downvoters會改變他們的投票,一旦他們看到你的編輯:) – 2013-03-28 05:54:01

回答

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