2016-03-06 160 views
0

我試圖瞭解在R循環和功能,因此我給自己定下了以下情況:我有一對相關矩陣:對於R中對相關矩陣環

dados<-matrix(rnorm(100),5,5) 
colnames(dados)<-c('A','B','C','D','E') 
rownames(dados)<-c('A','B','C','D','E') 
dados 
cor<-cor(dados) 

我想用循環以及是否保留了我的cor對象的值> 0.5的變量的保留組合條件。但是,我無法找到一種方法來將矩陣的行和列中的成對的camparisson重新定位。

我曾嘗試下面的代碼:

**的#是我不能化解的情況......

for (i in 1:nrow(cor)){ 
for (j in 1:ncol(cor)){ 

    # Here I think that I need args for compare each row with each column of my cor matrix, but I can't find these lines! 

    if (cor[i,j]>0.5){ 

    # Here I think that need a new matrix with 3 columns for combine variables of row (A to E), column(A to E) and values (> 0.5). I' cant find these lines too! 
    } 
    } 
} 

有人幫我想想辦法解決這個問題?

感謝您的幫助!

+1

爲什麼你就不能使用沒有循環部分的'cor(dados)> .5'?另外,最好不要因爲明顯的原因將相關矩陣命名爲「cor」。 –

回答

0

你顯然並不需要一個循環:

set.seed(12) 
dados   <- matrix(rnorm(100), 5, 5) 
colnames(dados) <- c('A', 'B', 'C', 'D', 'E') 
r    <- cor(dados) 

可以使用which索引的相關矩陣是元素大於0.5

inds <- which(r > .5, arr.ind = TRUE) # arr.ind = TRUE will return you a matrix of indices 
r2  <- r[inds] 
rows <- rownames(r)[inds[, 1]] 
cols <- colnames(r)[inds[, 2]] 
result <- cbind(rows, cols, r2)