« [Python]絶対値を求める | トップページ | [Python]累乗を求める »

2022年10月12日 (水)

[R]最小二乗法による正規線形回帰モデルのパラメーターの推定(「線形回帰分析」、pp.14-17)

表1.1のデータのファイルをカレントディレクトリに置いて行うこと。

> dtf <- read.csv("table1_1.csv", header = TRUE)
> xxi <- log(as.double(dtf$NIC))
> yyi <- log(as.double(dtf$CO))
> n <- nrow(dtf)
> ssxx <- sum(xxi)
> ssyy <- sum(yyi)
> ssxx2 <- sum(xxi ^ 2)
> ssyy2 <- sum(yyi ^ 2)
> ssxxyy <- sum(xxi * yyi)
> xxim <- ssxx / n
> yyim <- ssyy / n
> ssx2 <- ssxx2 - ssxx ^ 2 / n
> ssy2 <- ssyy2 - ssyy ^ 2 / n
> ssxy <- ssxxyy - ssxx * ssyy / n
> bh <- ssxy / ssx2
> ah <- yyim - bh * xxim
> yyhi <- ah + bh * xxi
> ei <- yyi - yyhi
> ri <- ei / yyi * 100
> ai2 <- ei ^ 2 / sum(ei ^ 2) * 100
> #
> cat(sprintf("β^ = %.6f\n", bh))
β^ = 1.054475
> cat(sprintf("α^ = %.6f\n", ah))
α^ = 2.663670
> s <- sprintf("%7.5f %7.5f %8.5f %6.2f %5.2f", yyi, yyhi, ei, ri, ai2)
> for (i in 1:n) cat(sprintf("%2d %s\n", i, s[i]))
1 2.61007 2.50463 0.10544 4.04 2.49
2 2.80940 2.72511 0.08429 3.00 1.59
3 3.15700 3.41028 -0.25328 -8.02 14.35
4 2.32239 2.24138 0.08101 3.49 1.47
5 1.68640 1.69746 -0.01106 -0.66 0.03
6 2.70805 2.70503 0.00302 0.11 0.00
7 2.19722 2.37428 -0.17706 -8.06 7.01
8 2.50960 2.60958 -0.09998 -3.98 2.24
9 2.79117 2.78317 0.00799 0.29 0.01
10 2.73437 2.68455 0.04982 1.82 0.56
11 2.56495 2.67416 -0.10921 -4.26 2.67
12 2.66723 2.55257 0.11466 4.30 2.94
13 2.30259 2.07093 0.23166 10.06 12.00
14 2.32239 2.40167 -0.07929 -3.41 1.41
15 2.25129 2.34616 -0.09487 -4.21 2.01
16 0.40547 0.51231 -0.10684 -26.35 2.55
17 2.91777 2.90737 0.01040 0.36 0.02
18 2.53370 2.74482 -0.21113 -8.33 9.97
19 2.86220 2.62062 0.24158 8.44 13.06
20 1.58924 1.74891 -0.15968 -10.05 5.70
21 2.76632 2.67416 0.09216 3.33 1.90
22 2.14007 2.14245 -0.00238 -0.11 0.00
23 2.36085 2.27239 0.08846 3.75 1.75
24 2.63189 2.68455 -0.05266 -2.00 0.62
25 2.70136 2.45441 0.24695 9.14 13.64
> #
> plot(xxi, yyi, xlim = c(-2, 0.7), ylim = c(0.4, 3.5), pch = 20)
> idx <- order(xxi)
> lines(xxi[idx], yyhi[idx])

Fig1_9

« [Python]絶対値を求める | トップページ | [Python]累乗を求める »

R(本の計算を再現)」カテゴリの記事

コメント

コメントを書く

コメントは記事投稿者が公開するまで表示されません。

(ウェブ上には掲載しません)

« [Python]絶対値を求める | トップページ | [Python]累乗を求める »

無料ブログはココログ