【发布时间】: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) > .5而不使用循环部分?此外,出于显而易见的原因,最好不要将相关矩阵命名为cor。