0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rの対話コンソールで最小2乗法を使った回帰分析

Last updated at Posted at 2019-10-13

はじめに

Rコンソールの対話プログラムで最小2乗法を使って1次関数を解くという変態的なことをしました。

今回は回帰直線を試すというもとで行うので事実とは異なりますが女子の平均身長が0歳から40歳まで伸び続けると仮定して分析を行っています:relaxed:

環境

R version3.4.4

###コード
XXはXの2乗 YYはYの2乗 EXはXの平均値 EYはYの平均値 EXYはX×Yの平均値 EX2はXの2乗の平均値 E2XはXの平均値の2乗を表します

> age <- c(13,14,15,16,17)
> age
[1] 13 14 15 16 17
> height <-c(155,156.5,157.1,157.7,158)
> height
[1] 155.0 156.5 157.1 157.7 158.0
> XY<-age*height
> XY
[1] 2015.0 2191.0 2356.5 2523.2 2686.0
> XX<-age*age
> XX
[1] 169 196 225 256 289
> YY<-height*height
> YY
[1] 24025.00 24492.25 24680.41 24869.29 24964.00
> EXY<-mean(XY)
> EXY
[1] 2354.34
> EX<-mean(age)
> EX
[1] 15
> EY<-mean(height)
> EY
[1] 156.86
> EX2<-mean(XX)
> E2X<-EX*EX
> E2X
[1] 225
> EX2
[1] 227
> a<-(EXY-EX*EY)/(EX2-E2X)
> a
[1] 0.72
> b<-EY-a*EX
> b
[1] 146.06
> y<-function(x){return(a*x+b)}
> plot(y,0,40)
y = 0.72x + 146.06

###得られた1次関数をグラフにすると...

leastSquaresMethod.png

横軸xが年齢縦軸yが身長です。成長によって身長が伸びるという相関関係が確認できたと思います。

points(age, height)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?