Find the Line Equation From 2 Points in R

Suppose we want to know the equation of the line that passes through 2 points A and B, such that:

A = c(2, 54)
B = c(14, 25)

Quick solution

# step 1: separate the x and y coordinates
xs = c(A[1], B[1])
ys = c(A[2], B[2])

# step 2: fit a linear equation that predicts ys using xs
lm(ys ~ xs)

Output:

Call:
lm(formula = ys ~ xs)

Coefficients:
(Intercept)           xs  
     58.833       -2.417 

So, the equation of the line that passes through A and B is:

\(f(x) = -2.417x + 58.833\)

To get more digits after the decimal point, use:

# print the maximum number of significant digits
options(digits = 22)

lm(ys ~ xs)

Output:

Call:
lm(formula = ys ~ xs)

Coefficients:
        (Intercept)                   xs  
58.8333333333333144  -2.4166666666666656 

Mathematical solution

In order to find the linear equation: \(y = mx + b\), we can use the following formula for finding the slope m:

\(m = \frac{y_B – y_A}{x_B – x_A}\)

# calculating the slope
m = (B[2] - A[2]) / (B[1] - A[1])

# print(m) outputs: -2.416667

And the y intercept b is:

\(b = y – mx\)

So, \(b = y +2.416667x\)

Next, we can use either point A or B to solve the equation.

Let’s use A:

Since the equation has to pass through A(2, 54) then:

# A(2, 54) is a solution of b = y - mx, so:
b = 54 + 2.416667 * 2

# print(b) outputs: 58.83333

So, the equation of the line that passes through A and B is:

\(f(x) = -2.416667x + 58.83333\)

Example

The monthly income (in US dollars) of an employee in a factory can be modeled with a linear function f(x), where x is the number of hours worked.

Last month:

  • Employee A worked 160 hours and made 1,800$.
  • Employee B worked 200 hours and made 2,000$.

Find the equation of the function f(x).

Solution:

A = c(160, 1800)
B = c(200, 2000)

# grouping the x and y coordinates
xs = c(A[1], B[1])
ys = c(A[2], B[2])

# finding the equation of the line
lm(ys ~ xs)

Output:

Call:
lm(formula = ys ~ xs)

Coefficients:
(Intercept)           xs  
       1000            5

So, \(f(x) = 1000 + 5x\)

Interpretation:

The employees’ monthly base salary is 1,000$, plus 5 times the number of hours they work per month.

Further reading