2014-07-02 27 views
0

假設我有二元向量,需要將它們與Kappa函數進行類似比較。如何通過循環比較R中對象的所有可能組合

library(asbio) 
A <- c(0,1,1,1,1,1,0) 
B <- c(0,0,1,0,1,0,1) 
C <- c(1,0,0,1,1,0,0) 
D <- c(1,1,0,0,0,1,1) 
E <- c(1,0,0,1,1,0,1) 

enter image description here

Kappa(A,B)$ttl_agreement # 42% 

如何循環Kappa功能得到表中的所有可能比較

我希望得到的東西是這樣的:

A B C D E 
A 100 42 - - - 
B 42 100 - - - 
C - - 100 - - 
D - - - 100 - 
E - - - - 100 
+1

你可以,也沒有使用任何包這樣的:'sapply(seq_len(nrow(MAT)),功能(I)(colSums(墊[我] ==ŧ (mat))/ ncol(mat))* 100)'其中'mat = rbind(A,B,C,D,E)'。 –

回答

2

可以使用outer功能

library(asbio) 

A <- c(0,1,1,1,1,1,0) 
B <- c(0,0,1,0,1,0,1) 
C <- c(1,0,0,1,1,0,0) 
D <- c(1,1,0,0,0,1,1) 
E <- c(1,0,0,1,1,0,1) 


M <- rbind(A,B,C,D,E) 

res <- outer(1:nrow(M), 
      1:nrow(M), 
      FUN=function(i,j){ 
       # i and j are 2 vectors of same length containing 
       # the combinations of the row indexes. 
       # e.g. (i[1] = 1, j[1] = 1) (i[2] = 1, j[2] = 2)) etc... 
       sapply(1:length(i), 
         FUN=function(x) Kappa(M[i[x],],M[j[x],])$ttl_agreement) 
      }) 
row.names(res) <- c('A','B','C','D','E') 
colnames(res) <- c('A','B','C','D','E') 

#> res 
      A   B   C   D   E 
# A 100.00000 42.85714 42.85714 28.57143 28.57143 
# B 42.85714 100.00000 42.85714 28.57143 57.14286 
# C 42.85714 42.85714 100.00000 28.57143 85.71429 
# D 28.57143 28.57143 28.57143 100.00000 42.85714 
# E 28.57143 57.14286 85.71429 42.85714 100.00000 

編輯:

如果你喜歡一個for循環(I」 d建議運行一些測試以查看哪種方法更快),則可以使用expand.grid生成組合,然後重複在他們填寫矩陣

M <- rbind(A,B,C,D,E) 

res <- matrix(NA,nrow=5,ncol=5) # pre-allocate the matrix 
combs <- expand.grid(1:nrow(M),1:nrow(M)) 
for(i in 1:nrow(combs)){ 
    r <- combs[i,1] 
    c <- combs[i,2] 
    res[r,c] <- Kappa(M[r,],M[c,])$ttl_agreement 
} 
row.names(res) <- c('A','B','C','D','E') 
colnames(res) <- c('A','B','C','D','E') 
+0

正是我需要的,謝謝@digEmAll。 –

+0

嗨@digEmAll!我在我的問題中使用了你的代碼(看看是否有興趣):http://stats.stackexchange.com/questions/105655/how-to-cluster-objects-according-their-complex-shape –