tính toán hồi quy dưa trên dataset mtcars
đầu tiên tạo ra fuction hồi quy

linear_regression <- function(X, Y) {
  library(ggplot2)
  if (length(X) != length(Y)) {
    stop("Độ dài của X và Y phải bằng nhau.")
  }
    n <- length(X) # Số lượng quan sát
  mean_X <- mean(X) # Trung bình của X
  mean_Y <- mean(Y) # Trung bình của Y
  SS_xy <- sum((X - mean_X) * (Y - mean_Y)) # Tích chéo tổng (sum of squares) của (X - mean_X) và (Y - mean_Y)
  SS_xx <- sum((X - mean_X)^2) # Tổng bình phương (sum of squares) của (X - mean_X)
  
  b <- SS_xy / SS_xx
  a <- mean_Y - b * mean_X
  result <- list(
    slope = b,
    intercept = a,
    fitted_values = a + b * X,
    residuals = Y - (a + b * X),
    R_squared = (SS_xy^2) / (SS_xx * sum((Y - mean_Y)^2)),
    scatter_plot = ggplot(data.frame(X = X, Y = Y), aes(x = X, y = Y)) +
      geom_point(color = "blue") +
      geom_abline(intercept = a, slope = b, color = "red") +
      labs(title = "Biểu đồ Scatter và Đường Hồi Quy", x = "Biến Giải Thích (X)", y = "Biến Phản Hồi (Y)")
  )
  
  return(result)
}

dùng dataset mtcars

# Đọc bộ dữ liệu mtcars
data(mtcars)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
x <- mtcars$hp
y <- mtcars$mpg
de <- linear_regression(x,y)
print(de)
## $slope
## [1] -0.06822828
## 
## $intercept
## [1] 30.09886
## 
## $fitted_values
##  [1] 22.593750 22.593750 23.753631 22.593750 18.158912 22.934891 13.382932
##  [8] 25.868707 23.617174 21.706782 21.706782 17.817770 17.817770 17.817770
## [15] 16.112064 15.429781 14.406357 25.595794 26.550990 25.664022 23.480718
## [22] 19.864619 19.864619 13.382932 18.158912 25.595794 23.890087 22.389065
## [29] 12.086595 18.158912  7.242387 22.661978
## 
## $residuals
##  [1] -1.59374995 -1.59374995 -0.95363068 -1.19374995  0.54108812 -4.83489134
##  [7]  0.91706759 -1.46870730 -0.81717412 -2.50678234 -3.90678234 -1.41777049
## [13] -0.51777049 -2.61777049 -5.71206353 -5.02978075  0.29364342  6.80420581
## [19]  3.84900992  8.23597754 -1.98071757 -4.36461883 -4.66461883 -0.08293241
## [25]  1.04108812  1.70420581  2.10991276  8.01093488  3.71340487  1.54108812
## [31]  7.75761261 -1.26197823
## 
## $R_squared
## [1] 0.6024373
## 
## $scatter_plot