我试图了解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)
我想要使用循环,并且如果条件用于保留具有值&gt;的变量的组合。 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!
}
}
}
有人帮我思考解决这个问题的方法吗?
感谢您的帮助!
答案 0 :(得分:0)
你显然不需要循环:
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)