Viết 1 function

Mô hình hồi quy bội có dạng: Y=β1+β2X2+β3X3+..+βkXk+u

Kiểm định Durbin - Watson

Trong Eviews mỗi khi chạy hồi quy thì mặc định xuất hiện giá trị của Durbin-Watson Test – một kiểm định thường dùng đến khi đánh giá hiện tượng tự tương quan (Autocorrelation) – một vấn đề về lỗi mô hình rất phổ biến với chuỗi dữ liệu thời gian với cặp giả thuyết sau:

  H0: Phần dư của mô hình không có tự tương quan

  H1: Phần dư của mô hình có tự tương quan

Nếu cần thiết, trong R cũng có thể thực hiện kiểm định này với gói lmtest

linear_regression <- function(data, x_col, y_col) {
  # Chạy hồi quy tuyến tính
  lm_model <- lm(formula = paste(y_col, "~", x_col), data = data)
  # Trả về mô hình hồi quy tuyến tính
  return(summary(lm_model))
   
  
 

}
scatter <- function(data, x_col, y_col) {
  library(ggplot2) 
   # Vẽ đồ thị phân tán và đường hồi quy
  ggplot(data, aes_string(x = x_col, y = y_col)) +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, color = "blue") +
    labs(title = "Biểu đồ phân tán và đường hồi quy",
         x = x_col,
         y = y_col) +
    theme_minimal()
}
library(palmerpenguins)
penguins <- na.omit(penguins)
linear_regression(penguins,"flipper_length_mm","body_mass_g")
## 
## Call:
## lm(formula = paste(y_col, "~", x_col), data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1057.33  -259.79   -12.24   242.97  1293.89 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -5872.09     310.29  -18.93   <2e-16 ***
## flipper_length_mm    50.15       1.54   32.56   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 393.3 on 331 degrees of freedom
## Multiple R-squared:  0.7621, Adjusted R-squared:  0.7614 
## F-statistic:  1060 on 1 and 331 DF,  p-value: < 2.2e-16
scatter(penguins,"flipper_length_mm","body_mass_g")
## Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
## ℹ Please use tidy evaluation idioms with `aes()`.
## ℹ See also `vignette("ggplot2-in-packages")` for more information.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'