超過 2 個解釋變數

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")

散點圖:以長度、高度與質量著色

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)

變數兩兩之間的二因子交互作用

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 + 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 的迴歸分析中級

僅二因子交互作用

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 若要對解釋變數做平方轉換,請參考「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...