Finding where two linear fits intersect in R

后端 未结 4 1692
天命终不由人
天命终不由人 2020-12-03 09:10

I have two linear fits that I\'ve gotten from lm calls in my R script. For instance...

fit1 <- lm(y1 ~ x1)
fit2 <- lm(y2 ~ x2)

I\'d l

4条回答
  •  孤街浪徒
    2020-12-03 09:39

    Here's some high school geometry then ;-)

    # First two models
    df1 <- data.frame(x=1:50, y=1:50/2+rnorm(50)+10)
    m1 <- lm(y~x, df1)
    
    df2 <- data.frame(x=1:25, y=25:1*2+rnorm(25)-10)
    m2 <- lm(y~x, df2)
    
    # Plot them to show the intersection visually    
    plot(df1)
    points(df2)
    
    # Now calculate it!    
    a <- coef(m1)-coef(m2)
    c(x=-a[[1]]/a[[2]], y=coef(m1)[[2]]*x + coef(m1)[[1]])
    

    Or, to simplify the solve-based solution by @Dwin:

    cm <- rbind(coef(m1),coef(m2)) # Coefficient matrix
    c(-solve(cbind(cm[,2],-1)) %*% cm[,1])
    # [1] 12.68034 16.57181 
    

提交回复
热议问题