#Your data frame (4 variables instead of 10)
df<-data.frame(a=c(1:100),b=rpois(1:100,.2),c=rpois(1:100,.4),d=rpois(1:100,.8),e=2*c(1:100))
#setup
library(Hmisc)
library(corrplot)
df<-scale(df)# normalize the data frame. This will also convert the df to a matrix.
corr<-rcorr(df) # compute Pearson's (or spearman's corr) with rcorr from Hmisc package. I like rcorr as it allows to separately access the correlations, the # or observations and the p-value. ?rcorr is worth a read.
corr_r<-as.matrix(corr[[1]])# Access the correlation matrix.
corr_r[,1]# subset the correlation of "a" (=var1 ) with the rest if you want.
pval<-as.matrix(corr[[3]])# get the p-values
corrplot(corr_r,method="circle",type="lower",diag=FALSE,tl.col="black",tl.cex=1,tl.offset=0.1,tl.srt=45)# plot all pairs
corrplot(corr_r,p.mat = pval,sig.level=0.05,insig = "blank",method="circle",type="lower",diag=FALSE,tl.col="black",tl.cex=1,tl.offset=0.1,tl.srt=45)# plot pairs with significance cutoff defined by "p.mat"
2 回答
我的包
corrr
,有助于探索相关性,有一个简单的解决方案 . 我将使用mtcars数据集作为示例,并说我们要关注mpg
与所有其他变量的相关性 .这里,
correlate()
生成相关数据框,focus()
让您可以专注于某些变量与所有其他变量的相关性 .仅供参考,
focus()
与dplyr
包中的select()
类似,不同之处在于它会改变行和列 . 因此,如果您熟悉select()
,您会发现它很容易使用focus()
. 例如 . :另一种方法是使用库Hmisc和corrplot来获得所有对之间的相关性,重要性和漂亮的情节如下: