简体   繁体   中英

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

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)

Two issues.

  1. b0 and b1 don't exist when you call the function, so you can't pass them in as arguments---you can pass them in as strings, which is what switch expects. So when you call regression , call it as regression("b1", x, y) or regression("b0", x, y) .

  2. In the b0 = {...} section of code, you call an intermediate result b , but later try to reference b1 . Again, b1 doesn't exist, so call your intermediate result b1 , not b .

Address those issues, and I think your function will work just fine :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM