【问题标题】:how to regress a linear model by group and only change the slope but keep the intercept the same?如何按组回归线性模型,只改变斜率但保持截距不变?
【发布时间】:2020-08-16 01:16:25
【问题描述】:

例如,我想对这样的模型进行回归:

这是我按组回归的数据和方法:

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

但问题是,通过这种方法,我不能保持截距不变,只能改变斜率。我想知道如何回归如图所示的方程,它只有一个截距,但有根据“j”列的不同斜率。

谁能帮帮我?

【问题讨论】:

标签: r regression


【解决方案1】:

使用这个公式:

lm(y ~ x:j, df)

给予:

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

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

【讨论】:

    【解决方案2】:

    你的意思是这样的?

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

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2017-04-03
      • 2019-02-23
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      • 2015-11-01
      • 2017-03-01
      相关资源
      最近更新 更多