本文介绍了删除值后,将var格式保留为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用下面的代码(从.有人可以解释如何仅从相关矩阵的下半部分获取输出,并让其显示行名和列名而不是colN
吗?
I am trying to print out the values of a correlation matrix as an ordered list using the code below adapted from here. Can someone explain how to get output from only the lower half of the correlation matrix, and have it display row and column names instead of 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)
我想要的例子:
row names col names corr vales
col3 col2 0.60
col2 col1 -0.38
col3 col1 -0.72
推荐答案
使用lower.tri
索引数据.
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
如果必须更改名称,则将其全部包裹在setNames()
中:
If you must have the names changed, then just wrap it all in setNames()
:
setNames(as.data.frame.table(cors)[lower.tri(cors),], c("row","col","corr"))
这篇关于删除值后,将var格式保留为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!