1 Tạo function chạy mô hình hồi quy tuyến tính

lm_test <- function(data, x , y){
# Chạy hồi quy tuyến tính
  lm_result <- lm(formula = paste(y , '~', x), data = data)
# Vẽ đồ thị phân tán và đường hồi quy
  library(ggplot2)
  ss <- ggplot(data, aes_string(x=x, y=y))+
    geom_point()+
    geom_smooth(formula = y~x, method = 'lm')
list(summary(lm_result), ss)}

2 Thực hành

Chạy hồi quy cho 2 biến prestige và articles trong tập dữ liệu PhDPublications, nói về số lượng bài báo cáo các nghiên cứu sinh đã làm.

Trong đó:

prestige là chất lượng chương trình đào tạo

articles là số bài báo cáo các nghiên cứu sinh làm được

library(AER)
data(PhDPublications)
lm_test(data = PhDPublications,' prestige','articles')
## [[1]]
## 
## Call:
## lm(formula = paste(y, "~", x), data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.9106 -1.5489 -0.5561  0.5042 17.4855 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  1.24755    0.21026   5.933 4.21e-09 ***
## prestige     0.14352    0.06459   2.222   0.0265 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.922 on 913 degrees of freedom
## Multiple R-squared:  0.005379,   Adjusted R-squared:  0.004289 
## F-statistic: 4.937 on 1 and 913 DF,  p-value: 0.02653
## 
## 
## [[2]]