简体   繁体   中英

Find slope by linear regression of 2 matrices (R)

I have 2 matrices. One contains the quantities a client bought of products. The matrix looks like this quantitymatrix:

在此处输入图像描述

the other one contains unitprices at which a client bought the products. The matrix looks like this pricematrix:

在此处输入图像描述

How can I run a linear regression with the matrices so that I obtain the slope for each product?

Your data:

quantity <-  matrix(c(4,2,6, 9,4,3, 1,1,2, 3,1,5), 3, 4)
price <-  matrix(c(1,0.5,8, 4.2,1.2,2, 2,5,2, 1,2.5,1), 3, 4)

First, you have to transform your two matrices into a single data frame. (Although you can avoid that if you want, but I think it makes it much more straightforward if you do so):

df <-  data.frame(quantity = as.numeric(quantity), 
                    price = as.numeric(price), 
                    product = rep(1:4, each = 3), ID = 1:3)

Then, run the linear models by groups:

lms <-  by(df, df$product, FUN = function(x) lm(price~quantity, data = x)) 

And get the slopes:

slopes <- sapply(lms, coef)[2,]

If however, you want to keep the orignial matrices as they are, you can run a simple loop:

slopes <- numeric(dim(price)[2])
for (i in 1:dim(price)[2]) {
  model <- lm(price[,i]~quantity[,i])
  slopes[i] <- coef(model)[2]
}

NB: this solution assumes that the two matrices have identical dimensions.

And if you want to avoid loops, the following solution may be faster:

f <-  function(x,y) coef(lm(y~x))[2]
l <- function(m) lapply(seq_len(ncol(m)), function(i) m[,i])

mapply(f, l(quantity), l(price))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM