用 R 中的数据拟合自定义回归方程

Fitting custom regression equation with data in R

假设我有以下数据

  library(zoo)
  Dates = seq(as.Date('2000-01-01'), as.Date('2005-12-31'), by = '6 months')
  Data = rbind(data.frame(time = Dates, y = rnorm(length(Dates), 0, 10), month = as.factor(format(Dates, '%m')), type = 'A', M = log(12+0:11)),
                data.frame(time = Dates, y = rnorm(length(Dates), 0, 10), month = as.factor(format(Dates, '%m')), type = 'B', M = log(3+0:11)),
                data.frame(time = Dates, y = rnorm(length(Dates), 0, 10), month = as.factor(format(Dates, '%m')), type = 'C', M = log(2+0:11)),
                data.frame(time = Dates[3:10], y = rnorm(8, 0, 10), month = as.factor(format(Dates[3:10], '%m')), type = 'D', M = log(10+0:7)))
  XX = zoo(rt(length(Dates), 2, 0), Dates)

和一个假设模型

y[t, type] = Beta[0] + Beta[1] * xx[t] + Beta[2] * type + Beta[3] * month + Beta[4] * M[t, type] + error

我正在尝试使用 lm() 函数根据数据估计上述模型的参数,但不确定如何在 lm() 函数中拟合上述方程。

以上型号可以使用lm()功能吗?还有哪些其他选择?

这似乎不是一个特别不寻常的模型规格。你想要:

y[t, type] = Beta[0] + Beta[1] * xx[t] + Beta[2] * type + 
    Beta[3] * month + Beta[4] * M[t, type] + error

鉴于您的数据设置方式,您可以将其视为按 i:

编制的索引
y[t[i], type[i]] = ... Beta[1] * xx[t[i]] + Beta[2] * type[i] + ... +
    Beta[4]* M[t[i], type[i]] ...

对应lm中的这个公式(其中1代表截距/Beta[0]项,无论如何都会默认加上,除非你加0-1 到你的公式)。

y ~ 1 + xx + type + month + M

有一件事与您想要的规范不符,因为 type 是一个 分类 变量(因子),具有两个以上的水平,所以赢了不是单个参数 Beta[2]:相反,R 会在内部将 type 转换为一系列 (n_level-1) 虚拟变量(搜索 questions/material 关于“对比”以了解此过程) 更好)。