R 散布図、共分散

2つの変数同士の関係について。

データは、『Rによるやさしい統計学https://www.amazon.co.jp/dp/4274067106 3章から。

勉強する内容

  • 相関: 量的変数同士の関係
  • 連関: 質的変数同士の関係
  • 正の相関: 散布図を描いて右上がりの傾向
  • 負の相関: 散布図を描いて右下がりの傾向
  • 無相関
  • plot(): 散布図
  • 相関係数: 相関の強さの程度を表す数値
  • 共分散: 「偏差の積の平均」
  • cov(): 共分散(不偏共分散)

共分散 Covariance

{ \displaystyle
s_{xy} =\frac{ ( x_1 - \bar{x} )( y_1 - \bar{y} ) + ( x_2 - \bar{x} )( y_2 - \bar{y}) + \cdots + ( x_n - \bar{x} )( y_n - \bar{y}) }{n}
}

すなわち、

{ \displaystyle
s_{xy} = \frac{1}{n}  \sum_{i=1}^{n} ( x_i - \bar{x} )( y_i - \bar{y} )
}

Rのプログラミング

s_test1 <- c(6,10,6,10,5,3,5,9,3,3,11,6,11,9,7,5,8,7,7,9)
s_test2 <- c(10,13,8,15,8,6,9,10,7,3,18,14,18,11,12,5,7,12,7,7)
p_test1 <- c(13,14,7,12,10,6,8,15,4,14,9,6,10,12,5,12,8,8,12,15)

# 散布図を描く
png("plot3-1.png", width = 500, height = 500)
plot(s_test1,s_test2)
dev.off() 

png("plot3-2.png", width = 500, height = 500)
plot(p_test1,s_test1)
dev.off() 

png("plot3-3.png", width = 500, height = 500)
plot(p_test1,s_test2)
dev.off() 
# 共分散(nで割った場合)
covariance_1_2 <- sum((s_test1 - mean(s_test1)) * (s_test2 - mean(s_test2))) / length(s_test1)
covariance_1_2
# 共分散(nで割った場合)別の求め方
covariance_1_2<- mean((s_test1 - mean(s_test1)) * (s_test2 - mean(s_test2)))
covariance_1_2
# 共分散(n-1で割った場合)
cov(s_test1,s_test2)
# 共分散(nで割った場合)別の求め方
cov(s_test1,s_test2) *  (length(s_test1)-1)/ length(s_test1)

実行結果

> 
> s_test1 <- c(6,10,6,10,5,3,5,9,3,3,11,6,11,9,7,5,8,7,7,9)
> s_test2 <- c(10,13,8,15,8,6,9,10,7,3,18,14,18,11,12,5,7,12,7,7)
> p_test1 <- c(13,14,7,12,10,6,8,15,4,14,9,6,10,12,5,12,8,8,12,15)
> 
> png("plot3-1.png", width = 500, height = 500)
> plot(s_test1,s_test2)
> dev.off() 
pdf 
  2 
> 
> png("plot3-2.png", width = 500, height = 500)
> plot(p_test1,s_test1)
> dev.off() 
pdf 
  2 
> 
> png("plot3-3.png", width = 500, height = 500)
> plot(p_test1,s_test2)
> dev.off() 
pdf 
  2 
> covariance_1_2 <- sum((s_test1 - mean(s_test1)) * (s_test2 - mean(s_test2))) / length(s_test1)
> covariance_1_2
[1] 7.55
> covariance_1_2<- mean((s_test1 - mean(s_test1)) * (s_test2 - mean(s_test2)))
> covariance_1_2
[1] 7.55
> cov(s_test1,s_test2)
[1] 7.947368
> cov(s_test1,s_test2) *  (length(s_test1)-1)/ length(s_test1)
[1] 7.55
> 

f:id:momozuka:20170208153523p:plain

f:id:momozuka:20170208153530p:plain

f:id:momozuka:20170208153537p:plain