Search code examples
rparametersregressionlinear-regressionestimation

How to calculate b0 and b1 in Simple Linear Regression With R?


I'm trying to create a program with R to calculate manually b0 and b1 in Simple Linear Regression with Least Square Method.

regression=function(num,x,y)
switch(num,
  b1 = {n = 5
        b = (n*sum(x*y)-sum(x)*sum(y))/(n*sum(x^2)-sum(x)^2)
        print(b)},
  b0 = {n = 5
        b = (n*sum(x*y)-sum(x)*sum(y))/(n*sum(x^2)-sum(x)^2)
        a = mean(y)-b1*mean(x)
        print(a)}
)
x = c(1, 2, 3, 4, 5)
y = c(2, 1, 4, 5, 3)
regression(b1, x, y)
regression(b0, x, y)

But it fails


Solution

  • A simpler way of defining your function is as follows,

    regression=function(num,x,y){
      n=num
      b1 = (n*sum(x*y)-sum(x)*sum(y))/(n*sum(x^2)-sum(x)^2)
      b0=mean(y)- b1*mean(x)
      return(c(b0,b1))
    
    }
    

    With this, you can get a vector containing your b0 and b1. In the code below, I have shown how you can access this and plot the resulting regression line.

    x = c(1, 2, 3, 4, 5)
    y = c(2, 1, 4, 5, 3)
    
    b0<-regression(5,x,y)[1]
    b1<-regression(5,x,y)[2]
    
    regression_line<-b0+b1*x
    
    plot(x,y)
    lines(regression_line)