【问题标题】:Linear regression with product of factor and independent variable具有因子和自变量乘积的线性回归
【发布时间】:2013-04-15 05:25:46
【问题描述】:

我正在尝试估计一个需求模型:

d_t^k = a_t - b^k p_t^k + e_t^k

索引t 表示周数,k 表示产品编号。每个产品d_t^k 的需求取决于所有产品a_t 共享的一般季节性,并且是该周产品价格p_t^k 的仿射函数,加上一些正常的随机误差e_t^k .

但是,如果我使用以下 lm 函数调用,它会为 price 提供一个系数 b,而我想要的是每个产品的一个系数 b^k 对于 price^k

lm(demand ~ factor(week) + price, data = df)

模型的正确表达方式是什么?

lm(demand ~ factor(week) + factor(product) * price, data = df)

我猜上面的方法会起作用,但我找不到任何文档告诉我那里发生了什么。

作为一个具体的例子,我有以下代码在稍微不同的需求模型上运行 d_t^k = a_t + a^k - b^k p_t^k + e_t^k

# Generate fake prices and sales, and estimate the coefficients of
# the demand model.

number.of.items <- 20 # Must be a multiple of 4
number.of.weeks <- 5
coeff.item.min <- 300
coeff.item.max <- 500
coeff.price.min <- 1.4
coeff.price.max <- 2
normal.sd <- 40
set.seed(200)

# Generate random coefficients for the items
coeff.item <- runif(number.of.items, coeff.item.min, coeff.item.max)
coeff.price <- runif(number.of.items, coeff.price.min, coeff.price.max)
coeff.week <- 50 * 1:number.of.weeks

# Row is item, column is week
week.id.matrix <- outer(rep(1, number.of.items), 1:number.of.weeks)
item.id.matrix <- outer(1:number.of.items, rep(1, number.of.weeks))
price.matrix <- rbind(
  outer(rep(1, number.of.items / 4), c(100, 100, 90, 90, 80)),
  outer(rep(1, number.of.items / 4), c(100, 90, 90, 80, 60)),
  outer(rep(1, number.of.items / 4), c(100, 85, 85, 60, 60)),
  outer(rep(1, number.of.items / 4), c(100, 75, 60, 45, 45))
)
coeff.week.matrix <- outer(rep(1, number.of.items), coeff.week)
coeff.price.matrix <- outer(coeff.price, rep(1, number.of.weeks))
coeff.item.matrix <- outer(coeff.item, rep(1, number.of.weeks))
sales.matrix <- coeff.week.matrix +
  coeff.item.matrix -
  coeff.price.matrix * price.matrix +
  matrix(rnorm(number.of.weeks * number.of.items, 0, normal.sd),
         number.of.items, number.of.weeks)


df <- data.frame(item = factor(as.vector(item.id.matrix)),
                 week = factor(as.vector(week.id.matrix)),
                 price = as.vector(price.matrix),
                 sales = as.vector(sales.matrix))

model <- lm(sales ~ week + item + price, data = df)
model <- lm(sales ~ week + item + factor(item) * price, data = df)

print(summary(model))

【问题讨论】:

    标签: r lm


    【解决方案1】:

    做了一些实验,好像

    lm(demand ~ factor(week) + factor(product) * price, data = df)
    

    确实有效。

    我不知道为什么我没想到它会更早起作用。

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2021-11-28
      • 2018-11-16
      • 2020-05-17
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 2020-03-06
      • 2018-07-04
      相关资源
      最近更新 更多