Finding where two linear fits intersect in R

后端 未结 4 1686
天命终不由人
天命终不由人 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:41

    I am a little surprised there isn't a built in function for this.

    Here is a rudimentary function (for lm results), using the same general method as Tommy above. This uses the simple substitution method for two lines in the form "y=mx+b" to find the common intersection at y (y1=y2 ; m1*x + b1 = m2*x + b2) and solves for x:

    Function definition

    # Linear model Intercept function
    lmIntx <- function(fit1, fit2, rnd=2) {
      b1<- fit1$coefficient[1]  #y-int for fit1
      m1<- fit1$coefficient[2]  #slope for fit1
      b2<- fit2$coefficient[1]  #y-int for fit2
      m2<- fit2$coefficient[2]  #slope for fit2
      if(m1==m2 & b1==b2) {print("Lines are identical")
      } else if(m1==m2 & b1 != b2) {print("Lines are parallel")
      } else {
        x <- (b2-b1)/(m1-m2)      #solved general equation for x
        y <- m1*x + b1            #plug in the result
        data.frame(x=round(x, rnd), y=round(y, rnd))
      }
    }
    

    Test:

    line1 <- data.frame(x=c(0,1), y=c(0,2))
    line2 <- data.frame(x=c(0,1), y=c(1,3))
    line3 <- data.frame(x=c(0,1), y=c(1,5))
    
    lmIntx(lm(line1$y~line1$x), lm(line2$y~line2$x))
    [1] "Lines are parallel"
    
    
    lmIntx(lm(line1$y~line1$x), lm(line1$y~line1$x))
    [1] "Lines are identical"
    
    lmIntx(lm(line1$y~line1$x), lm(line3$y~line3$x))
                   x  y
    (Intercept) -0.5 -1
    

提交回复
热议问题