R 散布図、共分散
2つの変数同士の関係について。
データは、『Rによるやさしい統計学』 https://www.amazon.co.jp/dp/4274067106 3章から。
勉強する内容
- 相関: 量的変数同士の関係
- 連関: 質的変数同士の関係
- 正の相関: 散布図を描いて右上がりの傾向
- 負の相関: 散布図を描いて右下がりの傾向
- 無相関
- plot(): 散布図
- 相関係数: 相関の強さの程度を表す数値
- 共分散: 「偏差の積の平均」
- cov(): 共分散(不偏共分散)
共分散 Covariance
すなわち、
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 >