Pearson相関係数Rコード実装
Pearson相関係数(Pearson Correlation Coefficient)
Pearson’s rは、2つのランダム変数間の線形相関の程度を反映するために、ピルソン相関係数(Pearson correlation coefficient)と呼ばれる.ピルソン相関係数を理解するには,まず共分散(Covariance)を理解しなければならない.共分散は2つのランダム変数の関係を反映することができ、1つの変数が別の変数とともに大きくなるか小さくなると、この2つの変数の共分散は正の値であり、この2つの変数の間に正の相関関係があり、逆の相関関係があることを示す.共分散の値が大きな正数であれば,(1)2つの変数の間に強い正の相関を示す(2)2つの変数の間に強い正の相関はなく,共分散の値が大きいのはXやYの標準差が大きいためであるが,いったいどの結論が正しいのか.XとY変数の標準差を共分散から取り除くだけでわかるのではないでしょうか.共分散は2つのランダム変数間の関係を教えてくれるが,変数間の相関の強弱を測定することはできない.従って,2つのランダム変数間の相関度合いをより良く測定するために,ピルソン相関係数を導入した.ピルソン相関係数は共分散を2つの変数の標準差で割ったものであることがわかる.コードは次のとおりです.
> setwd("F:\\CSDN\\blog")
> states <- state.x77[,1:5]
> cov(states) #
Population Income Illiteracy Life Exp Murder
Population 19931683.7588 571229.7796 292.8679592 -407.8424612 5663.523714
Income 571229.7796 377573.3061 -163.7020408 280.6631837 -521.894286
Illiteracy 292.8680 -163.7020 0.3715306 -0.4815122 1.581776
Life Exp -407.8425 280.6632 -0.4815122 1.8020204 -3.869480
Murder 5663.5237 -521.8943 1.5817755 -3.8694804 13.627465
> cor(states) # Pearson
Population Income Illiteracy Life Exp Murder
Population 1.00000000 0.2082276 0.1076224 -0.06805195 0.3436428
Income 0.20822756 1.0000000 -0.4370752 0.34025534 -0.2300776
Illiteracy 0.10762237 -0.4370752 1.0000000 -0.58847793 0.7029752
Life Exp -0.06805195 0.3402553 -0.5884779 1.00000000 -0.7808458
Murder 0.34364275 -0.2300776 0.7029752 -0.78084575 1.0000000
> cor(states,method = "spearman") # spearman
Population Income Illiteracy Life Exp Murder
Population 1.0000000 0.1246098 0.3130496 -0.1040171 0.3457401
Income 0.1246098 1.0000000 -0.3145948 0.3241050 -0.2174623
Illiteracy 0.3130496 -0.3145948 1.0000000 -0.5553735 0.6723592
Life Exp -0.1040171 0.3241050 -0.5553735 1.0000000 -0.7802406
Murder 0.3457401 -0.2174623 0.6723592 -0.7802406 1.0000000
> cor.test(states[,3],states[,5]) #
Pearson's product-moment correlation
data: states[, 3] and states[, 5]
t = 6.8479, df = 48, p-value = 1.258e-08
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.5279280 0.8207295
sample estimates:
cor
0.7029752
> #cor.test() ,psych
> #install.packages("psych")
> library(psych)
> corr.test(states,use = "complete")
Call:corr.test(x = states, use = "complete")
Correlation matrix
Population Income Illiteracy Life Exp Murder
Population 1.00 0.21 0.11 -0.07 0.34
Income 0.21 1.00 -0.44 0.34 -0.23
Illiteracy 0.11 -0.44 1.00 -0.59 0.70
Life Exp -0.07 0.34 -0.59 1.00 -0.78
Murder 0.34 -0.23 0.70 -0.78 1.00
Sample Size
[1] 50
Probability values (Entries above the diagonal are adjusted for multiple tests.)
Population Income Illiteracy Life Exp Murder
Population 0.00 0.44 0.91 0.91 0.09
Income 0.15 0.00 0.01 0.09 0.43
Illiteracy 0.46 0.00 0.00 0.00 0.00
Life Exp 0.64 0.02 0.00 0.00 0.00
Murder 0.01 0.11 0.00 0.00 0.00
To see confidence intervals of the correlations, print with the short=FALSE option