我有2个矩阵。其中包含客户购买的产品数量。矩阵看起来像这样quantitymatrix,
另一个包含客户购买产品的单价。矩阵看起来像这样pricematrix。
如何对矩阵进行线性回归,以便获得每个乘积的斜率。
非常感谢!
您的数据:
quantity <- matrix(c(4,2,6, 9,4,3, 1,1,2, 3,1,5))
price <- matrix(c(1, 0.5, 8, 4.2, 1.2, 2, 2, 5,2, 1, 2.5, 1))
首先,您必须将两个矩阵转换为单个数据帧。 (尽管您可以避免这种情况,但是我认为这样做可以使操作更加简单):
df <- data.frame(quantity = as.numeric(quantity),
price = as.numeric(price),
product = rep(1:4, each = 3), ID = 1:3)
然后,按组运行线性模型:
lms <- by(df, df$product, FUN = function(x) lm(price~quantity, data = x))
并获得坡度:
slopes <- sapply(lms, coef)[2,]