您的数据:
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,]