SSブログ

【R】回帰分析の結果オブジェクトの中味を抽出する方法 [データサイエンス、統計モデル]

統計の講師をしていて、なるほど!と思う質問を受けることがあります。
せっかくなので、その中からピックアップして紹介できればと思います。

【質問】
統計ツール(R)回帰分析などを行った際に、summaryで表示される内容を抽出するにはどうしたら良いか?

【回答】
iris のデータを使って解説していきます。

iris はRで用意されているデータです。

> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

線形回帰を行い、summaryで分析結果を表示します。

> lm.out <- lm(Sepal.Length~Species, iris)
> summary(lm.out)

Call:
lm(formula = Sepal.Length ~ Species, data = iris)

Residuals:
Min 1Q Median 3Q Max
-1.6880 -0.3285 -0.0060 0.3120 1.3120

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 5.0060 0.0728 68.762 < 2e-16 ***
Speciesversicolor 0.9300 0.1030 9.033 8.77e-16 ***
Speciesvirginica 1.5820 0.1030 15.366 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.5148 on 147 degrees of freedom
Multiple R-squared: 0.6187, Adjusted R-squared: 0.6135
F-statistic: 119.3 on 2 and 147 DF, p-value: < 2.2e-16

lm.out の構造を確認すると・・・

> str(lm.out)
List of 13
$ coefficients : Named num [1:3] 5.01 0.93 1.58
$ residuals : Named num [1:150] 0.094 -0.106 -0.306 -0.406 -0.006 ...
$ effects : Named num [1:150] -71.5659 0.8025 7.91 -0.3826 0.0174 ...
$ rank : int 3
$ fitted.values: Named num [1:150] 5.01 5.01 5.01 5.01 5.01 ...
$ assign : int [1:3] 0 1 1
$ qr :List of 5
$ df.residual : int 147
$ contrasts :List of 1
$ xlevels :List of 1
$ call : language lm(formula = Sepal.Length ~ Species, data = iris)
$ terms :Classes 'terms', 'formula' language Sepal.Length ~ Species
$ model :'data.frame': 150 obs. of 2 variables:

13のリストを確認できます。

まずは、推定された回帰式の係数を確認します。

> lm.out$coefficients
(Intercept) Sepal.Width Petal.Length Petal.Width Speciesversicolor Speciesvirginica
2.1712663 0.4958889 0.8292439 -0.3151552 -0.7235620 -1.0234978

$coefficients で回帰係数の値を抽出できますが、さらに、特定の回帰係数を抽出するには、
[[" *** "]] で取り出すこともできます。

> lm.out$coefficients[["Sepal.Width"]]
[1] 0.4958889

取り出した値に対して、演算することも可能で、下記のように書くと、10倍した値を取り出すこともできます。

> lm.out$coefficients[["Sepal.Width"]] * 10
[1] 4.958889

nice!(1)  コメント(0) 
共通テーマ:学問

nice! 1

コメント 0