LoginSignup
0
0

More than 5 years have passed since last update.

変数間の相関係数をリストとして大きい順に並べる

Last updated at Posted at 2018-07-16

やりたいこと

重回帰分析をするとき、多重共線性を避けるために相関が高い変数を見つける必要がある。
VIFを計算するライブラリもあるが、ここでは相関係数(の絶対値)を大きい順に並べたリストの作成方法を紹介する。

なお、このページはStack Overflowの以下記事を参考にしています。
Show correlations as an ordered list, not as a large matrix | Stack Overflow

サンプル

データの準備

df = data.frame(a=1:10,b=20:11*20:11,c=runif(10),d=runif(10),e=runif(10)*1:10)
z = cor(df)

相関係数の計算

cor()関数を使うと下のようなマトリクスができる。
5×5のマトリクスぐらいなら人間の目で相関の高い変数を見つけることも可能だが、これより変数の数が増えると厳しい。

           a          b           c           d          e
a  1.0000000 -0.9966867 -0.38925240 -0.35142452  0.2594220
b -0.9966867  1.0000000  0.40266637  0.35896626 -0.2859906
c -0.3892524  0.4026664  1.00000000  0.03958307  0.1781210
d -0.3514245  0.3589663  0.03958307  1.00000000 -0.3901608
e  0.2594220 -0.2859906  0.17812098 -0.39016080  1.0000000

リストへの変換

z[lower.tri(z,diag=TRUE)]=NA  #Prepare to drop duplicates and meaningless information
z=as.data.frame(as.table(z))  #Turn into a 3-column table
z=na.omit(z)  #Get rid of the junk we flagged above
z=z[order(-abs(z$Freq)),]    #Sort by highest correlation (whether +ve or -ve)

以下のような形で出力を得られる。便利。

         Var1    Var2    Freq
6        a       b       -0.9966867
16       a       d       -0.7705183
17       b       d       0.7578559
11       a       c       0.5856587
12       b       c       -0.5721143
22       b       e       -0.4459712
18       c       d       -0.4237590
21       a       e       0.3861569
23       c       e       0.3011528
24       d       e       -0.2713602
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0