Home > Software engineering >  How can I solve a linear equation in R when I already know all the coefficients?
How can I solve a linear equation in R when I already know all the coefficients?

Time:11-14

This may be a stupid question but I can't figure out how to do this.

I have an equation with known coefficients, and I want to solve for the variable(s).

So basically, it will be like: 3050 .05(B-250) = 1088 .1(B-500)

I know how to do that by hand and already solved for B = 40150, but what I want is a way to solve for B in R (tidyverse) because I will need to do this around 30x with slight changes to the numbers.

How would I do this in the tidyverse? Previously I did the below, which did give me intercepts, but I believe these are wrong because it's an estimation of the coefficients, whereas in my case I KNOW the coefficients, I just don't know how to put them into an equation that R will solve for.

Thank you for recommendations!

What I did before that I think is wrong:

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))
  }
}

line1 <- data.frame(x=allplan_t1$bill, y=allplan_t1$ppt)
line2 <- data.frame(x=allplan_t1$bill, y=allplan_t1$spt) 
line3 <- data.frame(x=allplan_t1$bill, y=allplan_t1$vpt)

lmIntx(lm(line1$y~line1$x), lm(line2$y~line2$x)) 
# intersection of lines 1 and 2

lmIntx(lm(line2$y~line2$x), lm(line3$y~line3$x))
# intersection of lines 2 and 3

lmIntx(lm(line1$y~line1$x), lm(line3$y~line3$x))
# intersection of lines 1 and 3

CodePudding user response:

The easiest way is to do the algebra: a1 a2 * (B - a3) = a4 a5 * (B - a6) means

a1 <- c(3050, ...)
a2 <- c(0.05, ...)
etc.
B <- (a4 - a1   a2 * a3 - a4 * a6) / (a2 - a5)

Will solve them all at once without a loop.

  • Related