【问题标题】:For loop in pairwise correlation matrix in RR中成对相关矩阵中的for循环
【发布时间】:2016-03-06 16:40:36
【问题描述】:

我试图了解 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)

我想使用循环和 if 条件来保留我的 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!
    }
  }
} 

有人帮我想想解决这个问题的方法吗?

感谢您的帮助!

【问题讨论】:

  • 为什么不能只使用cor(dados) &gt; .5 而不使用循环部分?此外,出于显而易见的原因,最好不要将相关矩阵命名为 cor

标签: r for-loop


【解决方案1】:

你显然不需要循环:

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

您可以使用which 来索引相关矩阵中大于 .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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多