通过2个矩阵的线性回归找到斜率(R)

问题描述 投票:0回答:1

我有2个矩阵。其中包含客户购买的产品数量。矩阵看起来像这个数量矩阵:

enter image description here

另一个包含客户购买产品的单价。矩阵看起来像这个价格矩阵:

enter image description here

如何对矩阵进行线性回归,以便获得每个乘积的斜率?

r matrix linear-regression
1个回答
0
投票

您的数据:

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,]
© www.soinside.com 2019 - 2024. All rights reserved.