问题描述
尝试使用 vif() 函数,但如何获得预测变量对之间的相关性?
适合
解决方法
您可以使用 cor
函数轻松找到变量之间的相关性,并使用包 corrplot
library(corrplot)
df <-
data.frame(
x1 = round(runif(100,min = 100,max=170)),x2 = sample(1:10,100,replace = T),x3 = round(runif(100),2),y = round(runif(100),2)
)
cor(df)
corrplot::corrplot(cor(df),method = "color")
,
如果您只想要相关系数,则可以使用 cor
。如果您想全部使用,请使用 sapply
:
sapply(data[,c("X1","X2")],function(x) cor(x,data$X3))
,
有很多方法..
创建虚拟数据
df <-
data.frame(
x1 = round(runif(100,2)
)
使用 psych
包
library(psych)
pairs.panels(df,method = "pearson",# correlation method
hist.col = "#00AFBB",density = TRUE,# show density plots
ellipses = TRUE # show correlation ellipses
)
使用 GGally 包
library(GGally)
##GGally package
## Correlation matirx
ggcorr(df,nbreaks = 6,label = TRUE,label_size = 3,color = "grey50")
## Correlation Plots
ggpairs(df,columns = 1: ncol(df),title = NULL,upper = list(continuous = "cor"),lower = list(continuous = "smooth"),mapping = NULL)