Search code examples
rlinear-regression

How can I compute the formula of simple linear regression in R?


I have this data:

x <- c(1,3,5,8,9,0)
y <- c(5,8,9,7,4,3)
xy <- data.frame(X = x, Y = y)

I draw the simple linear regression line with this code:

library(ggplot2)
MyRegression <- ggplot(xy, aes(x = x, y = y))
MyRegression + geom_point() + geom_smooth(method='lm')

Also I want to have automatically the type of the equation y=a+bx. I know how to compute a and b (by using this formula), but I 'm wondering if I can do it automatically by using a simple command.

Thanks in advance!


Solution

  • To calculate a linear model, use the R-fucntion lm.

    mod <- lm(Y~X,data=xy)
    

    Now you want to calculate the fitted line. This is possible via

    lineData <- data.frame(x=xy$X,y=mod$coefficients[1]+mod$coefficients[2]*xy$X)
    

    You can add the line by using geom_line:

    ggplot(xy, aes(x = x, y = y)) + geom_point() + geom_line(data=lineData,mapping = aes(x=x,y=y),col="red",size=2)