mia_
mia_

Reputation: 21

how to regress a linear model by group and only change the slope but keep the intercept the same?

For example, I want to regress a model like that:

the model

this is my data and method to regress by group:

library(tidyverse)
library(plyr)
# create data
df = data.frame(y=c(1,3,2,5,6,8,7,9,10,15),x=c(1,2,2,3,6,8,8,9,10,12),j=c("type1","type1","type1","type2","type2","type2","type2","type3","type3","type3"))
# regress 
linear_fit <- function(df) {
  model <- lm(y ~ x, df)
  linear_coef <- coef(model)
  linear_coef <- data.frame(intercept = linear_coef[1], 
                           slope = linear_coef[-1])
  row.names(linear_coef) <- NULL
  linear_coef
}
outcome<-ddply(df,.(j),linear_fit)
outcome
    j       intercept   slope
1   type1   -0.500000   1.5000000
2   type2   3.328358    0.5074627
3   type3   -10.071429  2.0714286

but the question is, by this method I can not keep the intercept the same and only change the slope.I want to know how can I regress a equation like the picture shows, which only has one intercept but has different slopes according to the "j" column.

Can anyone help me out?

Upvotes: 2

Views: 359

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269694

Use this formula:

lm(y ~ x:j, df)

giving:

Call:
lm(formula = y ~ x:j, data = df)

Coefficients:
(Intercept)     x:jtype1     x:jtype2     x:jtype3  
     1.1402       0.5888       0.8237       1.0020  

Upvotes: 2

pseudospin
pseudospin

Reputation: 2767

You mean like this?

model <- lm(y ~ x:j, df)
summary(model)

Upvotes: 1

Related Questions