Assuming you want to use loops (to train or for another reason, because in this case you don’t need to use loops), you can save the results in a list.
Recreating your data (with set.seed()
for reproducibility):
set.seed(10)
dados <- matrix(rnorm(100),5,5)
colnames(dados) <- c('A','B','C','D','E')
rownames(dados) <- c('A','B','C','D','E')
cor <- cor(dados)
Traversing the loop and saving results in a list:
# lista para armazenar resultado
resultados <- list()
for (i in 1:nrow(cor)){
for (j in 1:ncol(cor)){
if (cor[i,j]>0.5){
# armazena no primeiro nível a linha e no segundo nível a coluna
resultados[[rownames(cor)[i]]][[colnames(cor)[j]]] <- cor[i,j]
}
}
}
resultados
$A
A C
1.0000000 0.7764006
$B
B E
1.000000 0.912793
$C
A C
0.7764006 1.0000000
$D
D
1
$E
B E
0.912793 1.000000
With the list at hand you can arrange the data however you want. For example, the simplest way to transform into a vector is with unlist()
.
unlist(resultados)
A.A A.C B.B B.E C.A C.C D.D E.B E.E
1.0000000 0.7764006 1.0000000 0.9127930 0.7764006 1.0000000 1.0000000 0.9127930 1.0000000
But remember that you do not need to use loops in this case. For example, a way to get the same result above would be:
indices <- which(cor > 0.5, arr.ind = TRUE)
res <- setNames(cor[indices], paste(colnames(cor)[indices[,2]], rownames(cor)[indices[,1]], sep = "."))
res
A.A A.C B.B B.E C.A C.C D.D E.B E.E
1.0000000 0.7764006 1.0000000 0.9127930 0.7764006 1.0000000 1.0000000 0.9127930 1.0000000