説明変数が3つ以上の場合

Rで学ぶ中級回帰分析

Richie Cotton

Data Evangelist at DataCamp

前回のおさらい

ggplot(
  fish,
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno")

長さ×高さ×質量の散布図(inferno)

Rで学ぶ中級回帰分析

種でファセット

ggplot(
  fish,
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno") +
  facet_wrap(vars(species))

種でファセットした散布図

Rで学ぶ中級回帰分析

交互作用のレベル

交互作用なし

lm(mass_g ~ length_cm + height_cm + species + 0, data = fish)

変数ペア間の2次の交互作用

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + 0, 
  data = fish
)

3変数すべての3次の交互作用

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + length_cm:height_cm:species + 0, 
  data = fish
)
Rで学ぶ中級回帰分析

すべての交互作用

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + length_cm:height_cm:species + 0, 
  data = fish
)
lm(
  mass_g ~ length_cm * height_cm * species + 0, 
  data = fish
)
Rで学ぶ中級回帰分析

2次の交互作用のみ

lm(
  mass_g ~ length_cm + height_cm + species + length_cm:height_cm + length_cm:species + height_cm:species + 0, 
  data = fish
)
lm(
  mass_g ~ (length_cm + height_cm + species) ^ 2 + 0, 
  data = fish
)
lm(
  mass_g ~ I(length_cm) ^ 2 + height_cm + species + 0, 
  data = fish
)
1 説明変数の2乗化は、"Introduction to Regression in R" 第2章 "Transforming variables" を参照
Rで学ぶ中級回帰分析

予測の流れ

mdl_mass_vs_all <- lm(mass_g ~ length_cm * height_cm * species * 0, data = fish)

explanatory_data <- expand_grid(
  length_cm = seq(5, 60, 6),
  height_cm = seq(2, 20, 2),
  species = unique(fish$species)
)

prediction_data <- explanatory_data %>% 
  mutate(mass_g = predict(mdl_mass_vs_all, explanatory_data))
Rで学ぶ中級回帰分析

予測の可視化

ggplot(
  fish,
  aes(length_cm, height_cm, color = mass_g)
) +
  geom_point() +
  scale_color_viridis_c(option = "inferno") +
  facet_wrap(vars(species)) +
  geom_point(
    data = prediction_data, 
    size = 3, shape = 15
  )

長さ×高さ×質量×種の散布図(予測点)

Rで学ぶ中級回帰分析

練習しましょう!

Rで学ぶ中級回帰分析

Preparing Video For Download...