R 中的公式

R 中的广义线性模型

Richard Erickson

Instructor

为何关注多元逻辑回归的公式?

  • 公式是回归的骨架
  • 不易掌握
  • 理解 model.matrix() 至关重要
R 中的广义线性模型

斜率

  • 为连续变量估计系数
    • 例如:height = c(72.3, 21.1, 3.7, 1.0)
  • 公式还需全局截距
  • 多个斜率:每个自变量各一个斜率
R 中的广义线性模型

截距

  • 用离散分组进行预测
  • 在 R 中为因子或字符:fish = c("red", "blue")
  • 单一截距有两种方式:
    • 基准截距 + 对比:y ~ x
    • 各组各自截距:y ~ x -1
R 中的广义线性模型

多个截距

  • 估计各组相对基准组的效应
  • 基准为因子中按字母排序的第一组
  • 默认每个变量一个基准组
    • y ~ x1 + x2
  • 可指定对所有组估计截距
    • y ~ x1+ x2 - 1
  • 第一变量对每组估计一个截距
R 中的广义线性模型

哑变量

  • 编码组别归属
  • 在底层使用(如 model.matrix()
  • 各组用 0/1 表示
  • 示例输入:color = c("red", "blue")
  • y ~ colors 的哑变量:
    • intercept = c(1, 1)
    • blue = c(0, 1)
  • y ~ colors - 1 的哑变量:
    • red = c(1, 0)
    • blue = c(0, 1)
R 中的广义线性模型

model.matrix()

  • model.matrix() 为我们完成繁重工作
  • R 公式的基础
model.matrix( ~ colors)
  (Intercept) colorsred
1           1         1
2           1         0
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$colors
"contr.treatment"
  • 顺序由因子水平决定
  • 可用 Tidyverse 或 factor() 更改顺序
R 中的广义线性模型

因子 vs 数值 的注意事项

  • R 认为变量是数值型
    • 例如:month = c(1, 2, 3)
month <- c( 1, 2, 3)
model.matrix( ~ month)
  (Intercept) month
1           1     1
2           1     2
3           1     3
attr(,"assign")
0 1
  • 需指定为因子或字符
    • 例如:month = factor(c( 1, 2, 3))
model.matrix( ~ month)
  (Intercept) month2 month3
1           1      0      0
2           1      1      0
3           1      0      1
attr(,"assign")
0 1 1
attr(,"contrasts")$month
"contr.treatment"
R 中的广义线性模型

¡Vamos a practicar!

R 中的广义线性模型

Preparing Video For Download...