Keep var format as matrix after deleting values

I am trying to print the values โ€‹โ€‹of a correlation matrix as an ordered list using the code below adapted from here . Can someone please explain how to get the output from only the bottom half of the correlation matrix, and whether they display the row and column names instead colN

?

set.seed(1)
df <- data.frame(
    col1 = rnorm(10),
    col2 = rnorm(10),
    col3=rnorm(10)
)
row.names(df)<-c("A","B","C","D","E","F","G","H","I","J")

cors<-cor(df)
library(reshape)
x <- subset(melt(cors), value != 1 | value != NA)
x <- x[with(x, order(-abs(x$value))),]
#x$value<-signif(x$value,2)
head(x)

      

An example of what I was hoping for:

row names col names  corr vales
col3      col2        0.60
col2      col1       -0.38
col3      col1       -0.72

      

+2


source to share


1 answer


Use lower.tri

to index your data.

cors <- cor(df)
as.data.frame.table(cors)[lower.tri(cors),]

#  Var1 Var2       Freq
#2 col2 col1 -0.3767034
#3 col3 col1 -0.7158385
#6 col3 col2  0.6040273

      



If you must change the names, then just wrap them in setNames()

:

setNames(as.data.frame.table(cors)[lower.tri(cors),], c("row","col","corr"))

      

+1


source







All Articles