Bing Image Creator で生成: Close up of yellow Cymbidium flowers, background is green grass field and blue sky, photo
の続きです。今回は R で単回帰分析をしましょう。infer パッケージのワークフローに沿ってやってみます。
https://infer.netlify.app/articles/observed_stat_examples#two-numerical-vars---slr
このサイトを参考にしています。
はじめに、slope_hat を求めます。
散布図を描いてみます。
geom_smooth() 関数で回帰直線を追加しました。この傾きが有意に0と違うかどうかが問題です。
null distribution を生成します。
null distribution と slope_hat(-0.00719) をグラフにします。
-0.00719 ってほとんど 0 かと思いましたが、けっこう 0 とは離れていることがグラフにするとわかります。
p値を計算します。
p値は0.05よりも小さい0.014です。なので、elder_index と gdp_growth は5%の有意水準で関係性があることがわかります。
95%信頼区間も求めてみます。
95%信頼区間を求めます。
-0.0128 ~ -0.00148 となりました。0を含んでいません。
グラフ表示します。
95%信頼区間が0を含んでいないことがわかります。
今回の分析で、老年化指数が大きいほど、県内総生産額対前年増加率は低い、という関係があることがわかりました。
今回は以上です。
次回は、
です。
初めから読むには、
です。
今回のコードは以下になります。
#
# 傾きの算出
slope_hat <- df |>
specify(gdp_growth ~ elder_index) |>
calculate(stat = "slope")
slope_hat
#
# 散布図
df |>
ggplot(aes(x = elder_index, y = gdp_growth)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
#
# null distribution の生成
set.seed(222)
null_dist <- df |>
specify(gdp_growth ~ elder_index) |>
hypothesize(null = "independence") |>
generate(reps = 1000, type = "permute") |>
calculate(stat = "slope")
#
# null distribution と slope_hat
visualize(null_dist) +
shade_p_value(obs_stat = slope_hat,
direction = "two-sided")
#
# p値の計算
null_dist |>
get_p_value(obs_stat = slope_hat,
direction = "two-sided")
#
# ブートストラップ法
set.seed(222)
boot_dist <- df |>
specify(gdp_growth ~ elder_index) |>
generate(reps = 1000, type = "bootstrap") |>
calculate(stat = "slope")
#
# 95%信頼区間
percentile_ci <- boot_dist |>
get_confidence_interval(level = 0.95,
type = "percentile")
percentile_ci
#
# ブートストラップ法と信頼区間
boot_dist |>
visualize() +
shade_confidence_interval(endpoints = percentile_ci) +
geom_vline(xintercept = 0.0, color = "red", linewidth = 1.5)
#