R: الانحدار الخطي R: دليل شامل لوظيفة lm()
آخر تحديث: 2026-08-26
في الدروس الثلاثة السابقة، تعرفنا على الإحصاء الوصفي، والتوزيعات الاحتمالية، واختبار الفرضيات — وكلها تتضمن «تحليل البيانات». في هذا الدرس، سننتقل إلى «استخدام البيانات للتنبؤ بالمستقبل» — الانحدار الخطي. هذا هو «أبرز» ما يميز لغة R. هل هذا الادعاء الإعلاني — «استثمار بقيمة 1,000,000 يولد مبيعات بقيمة 5,000,000» — موثوق؟ دعونا نحسبه بسطر واحد باستخدام
lm().
بعد الانتهاء من هذا الدرس، ستتمكن من استخدام لغة R لإجراء الانحدار الخطي، ووضع التوقعات، وتفسير المعاملات، واختبار الدلالة الإحصائية، وتشخيص النماذج — وهو ما يمثل 80% من العمل في مجال علم البيانات.
1. ما ستتعلمه
- مبادئ الانحدار الخطي (Y = β0 + β1X + ε)
- صيغة الدالة lm(): y ~ x
- تفسير معاملات دالة summary() (التقدير / الخطأ المعياري / قيمة p)
- التنبؤ بـ predict()
- تشخيص المتبقي: plot.lm
- الانحدار المتعدد
- التعامل مع المتغيرات الفئوية
- التطبيق العملي: نماذج توقعات المبيعات
2. قصة عن توقعات المبيعات
(1) نقطة الضعف: الإعلان مقابل المبيعات
يريد بوب توقع تأثير «الإنفاق الإعلاني» على «المبيعات»:
Advertising expenses(0K) Sales(0K)
1 3
2 5
3 7
4 9
5 12
"مجرد حدس" بأن "إنفاق 10,000 على الإعلانات سيحقق مبيعات بقيمة 20,000"؟ استخدم LM لحساب ذلك بدقة—
(2) الحل باستخدام لغة R
# 1. Model Building in One Line
model <- lm(sales ~ ad, data = df)
# 2. View the results in one line
summary(model)
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 1.0000 0.3536 2.828 0.0474 *
# ad 2.0000 0.1054 18.975 0.0001 ***
# ---
# Residual standard error: 0.3651
# Multiple R-squared: 0.9923
# 3. One-Line Forecast
predict(model, data.frame(ad = 10))
# [1] 21 ← invest $10,000Advertising Sales Forecast 210,000
3 أسطر من التعليمات البرمجية → نموذج + تنبؤ.
3. مبادئ الانحدار الخطي
(1) الصيغ الرياضية
Y = β₀ + β₁X + ε
│ │ │
│ │ └─ Error term (Residual)
│ └────── Slope (X increases by 1, Y changes by how much?)
└────────── Intercept (Y value when X=0)
graph LR
A[Actual data points] --> B[Linear Model Fitting]
B --> C[Find the Best Straight Line]
C --> D[Minimize the sum of squared residuals]
D --> E[Least Squares Method OLS]
style A fill:#cce5ff
style B fill:#d4edda
style C fill:#fff3cd
style D fill:#f8d7da
style E fill:#e1d4ff
(2) الأفكار الأساسية
أوجد خطًا مستقيمًا بحيث يكون «مجموع مربعات المسافات» من جميع النقاط إلى الخط في أدنى قيمة ممكنة (طريقة المربعات الصغرى العادية، OLS).
4. الاستخدام الأساسي لدالة lm()
(1) 4 أنواع من صيغ الصيغ الحسابية
# 1. y ~ x (Most Commonly Used)
lm(sales ~ ad, data = df)
# 2. y ~ x1 + x2 (Multiple)
lm(sales ~ ad + price, data = df)
# 3. y ~ x1 * x2 (Interaction)
lm(sales ~ ad * price, data = df)
# 4. y ~ . (All other variables)
lm(sales ~ ., data = df)
(2) الانحدار الأول
# Data
df <- data.frame(
ad = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
sales = c(3, 5, 7, 9, 12, 13, 15, 17, 19, 21)
)
# Build a model
model <- lm(sales ~ ad, data = df)
# Abstract
summary(model)
شرح تفصيلي للنتائج:
Call:
lm(formula = sales ~ ad, data = df)
Residuals:
Min 1Q Median 3Q Max
-0.4 -0.3 0.0 0.3 0.4
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.0000 0.2041 4.899 0.00106 **
ad 2.0000 0.0340 58.787 1.01e-12 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.3651 on 8 degrees of freedom
Multiple R-squared: 0.9977, Adjusted R-squared: 0.9974
F-statistic: 3456 on 1 and 8 DF, p-value: 1.008e-12
(3) تحليل 6 أرقام رئيسية
| الحقل | المعنى | الشرح |
|---|---|---|
| التقدير | تقدير المعامل | ad=2.0 يشير إلى أن زيادة قدرها 10,000 في نفقات الإعلان تؤدي إلى زيادة قدرها 20,000 في المبيعات |
| الخطأ المعياري | الخطأ المعياري للمعامل | دقة تقدير المعامل (كلما كان الرقم أصغر، كان ذلك أفضل) |
| قيمة t | إحصائية t | التقدير / الخطأ المعياري |
| Pr(>|t|) | قيمة p | احتمال أن يكون المعامل غير ذي دلالة إحصائية = 0 |
| R² | معامل التحديد | النسبة المئوية للتباين الذي يفسره النموذج (0–1) |
| إحصائية F | إحصائية F | دلالة النموذج الإجمالي |
5. التنبؤ بـ predict()
(1) التوقعات الأساسية
# Single-Point Forecast
predict(model, data.frame(ad = 10))
# [1] 21 ← invest $10,000Advertising Sales Forecast 210,000
# Multi-point Forecasting
new_data <- data.frame(ad = c(11, 12, 13, 14, 15))
predict(model, new_data)
# [1] 23 25 27 29 31
# Confidence Interval
predict(model, data.frame(ad = 10), interval = "confidence")
# fit lwr upr
# 1 21.000 20.751 21.249
(2) فترة التنبؤ
# Prediction Range (Includes uncertainty in individual predictions)
predict(model, data.frame(ad = 10), interval = "prediction")
# fit lwr upr
# 1 21.000 20.064 21.936 <- wider than confidence
6. تشخيص المتبقيات: plot.lm
(1) 4 مخططات تشخيصية رئيسية
par(mfrow = c(2, 2))
plot(model)
| الصورة | المعنى | ما ينبغي أن يحدث |
|---|---|---|
| 1. القيم المتبقية مقابل القيم المُقدَّرة | القيم المتبقية مقابل القيم المُقدَّرة | مبعثرة عشوائيًا (بدون نمط) |
| 2. مخطط QQ | توزيع البقايا الطبيعي | النقاط القريبة من الخط |
| 3. المقياس والموقع | التماثل في التباين | بالقرب من الخط الأفقي |
| 4. القيم المتبقية مقابل الرافعة الإحصائية | الرافعة الإحصائية وتأثيرها | تقع معظم النقاط بعيدًا عن الحدود |
(2) التشخيص الرئيسي
# Residual
residuals(model)
# Standardized Residuals
rstandard(model)
# Leverage Ratio
hatvalues(model)
# Cook's Distance (Impact Metrics)
cooks.distance(model)
7. الانحدار الخطي المتعدد
(1) الانحدار المتعدد
# Sales ~ Advertising expenses + Price + Season
df <- data.frame(
sales = c(100, 120, 130, 110, 140, 150, 130, 160, 170, 180),
ad = c(10, 12, 14, 11, 15, 16, 13, 17, 18, 19),
price = c(50, 48, 45, 49, 44, 43, 47, 42, 41, 40),
season = c("Spring", "Summer", "Autumn", "Winter", "Spring", "Summer", "Autumn", "Winter", "Spring", "Summer")
)
model <- lm(sales ~ ad + price + season, data = df)
summary(model)
(2) العناصر التفاعلية
# Includes interaction terms (ad:price)
model <- lm(sales ~ ad * price, data = df)
# Equivalent to sales ~ ad + price + ad:price
(3) الترميز التلقائي للمتغيرات الفئوية
R تحويل المتغير character تلقائيًا إلى متغير وهمي:
# season is a character vector, R automatically creates:
# seasonSummer, seasonAutumn, seasonWinter (Spring as the Baseline)
as.factor() التحويل الصريح للعوامل أكثر أمانًا من الأحرف الافتراضية.
8. اختيار النموذج
(1) معامل R المربع المعدل
# The more variables you add, R-squared gets bigger (even if the variables are irrelevant)
# Adjusted R-squared corrects this bias
summary(model)$adj.r.squared
(2) معيار المعلومات AIC
# AIC The smaller the model, the better
model1 <- lm(sales ~ ad, data = df)
model2 <- lm(sales ~ ad + price, data = df)
model3 <- lm(sales ~ ad + price + season, data = df)
AIC(model1, model2, model3)
# df AIC
# 1 3 85.32
# 2 4 78.45
# 3 6 72.18 ← Best
(3) العودة التدريجية
# Forward
step(lm(sales ~ 1, data = df),
scope = list(lower = ~ 1, upper = ~ ad + price + season),
direction = "forward")
# Back
step(model3, direction = "backward")
# Two-way
step(model1, scope = ~ ad + price + season, direction = "both")
9. التطبيق العملي: نموذج شامل للتنبؤ بالمبيعات
فيما يلي مثال على مسار عمل كامل يربط بين جميع مفاهيم الانحدار الخطي التي تمت تغطيتها في هذا الدرس.
▶ مثال: نموذج متكامل لتوقعات المبيعات
# ============================================
# Comprehensive Sales Forecasting Model
# Features: The Complete Linear Regression Process (Data Exploration -> Model -> Diagnosis -> Forecast)
# ============================================
library(ggplot2)
library(dplyr)
library(broom)
# 1. Prepare data
set.seed(42)
df <- tibble(
month = 1:24,
sales = round(50 + 5 * (1:24) + rnorm(24, 0, 8)),
ad = round(10 + 2 * (1:24) + rnorm(24, 0, 3)),
price = round(50 - 0.5 * (1:24) + rnorm(24, 0, 2)),
season = rep(c("Spring", "Summer", "Autumn", "Winter"), 6),
region = rep(c("Northern China", "East China", "South China", "Central China"), 6)
)
cat("=== Data Preview ===\n")
print(head(df, 3))
# 2. Data Exploration: Scatter Plot Matrix
cat("\n=== Correlation Analysis ===\n")
cor(df |> select(month, sales, ad, price))
cat("\n")
# 3. Simple Linear Regression
cat("=== Simple Regression: sales ~ ad ===\n")
model1 <- lm(sales ~ ad, data = df)
summary(model1)
# 4. Multiple Regression
cat("\n=== Multiple Regression: sales ~ ad + price + season ===\n")
model2 <- lm(sales ~ ad + price + season, data = df)
summary(model2)
# 5. Full Return
cat("\n=== Full Model: sales ~ ad + price + season + region ===\n")
model3 <- lm(sales ~ ad + price + season + region, data = df)
summary(model3)
# 6. Model Comparison
cat("\n=== Model Comparison ===\n")
cat("Model 1 (Advertisement Only): R-squared =", round(summary(model1)$r.squared, 3),
"Adjusted R-squared =", round(summary(model1)$adj.r.squared, 3), "\n")
cat("Model 2 (+Price+Season): R-squared =", round(summary(model2)$r.squared, 3),
"Adjusted R-squared =", round(summary(model2)$adj.r.squared, 3), "\n")
cat("Model 3 (+Region): R-squared =", round(summary(model3)$r.squared, 3),
"Adjusted R-squared =", round(summary(model3)$adj.r.squared, 3), "\n")
cat("AIC:\n")
print(AIC(model1, model2, model3))
# 7. Model Diagnostics
cat("\n=== Model 3 Residual Diagnosis ===\n")
par(mfrow = c(2, 2))
plot(model3)
par(mfrow = c(1, 1))
# 8. Forecast
cat("\n=== Forecast for Next Month ===\n")
future <- data.frame(
ad = 60,
price = 38,
season = "Autumn",
region = "Northern China"
)
prediction <- predict(model3, future, interval = "confidence")
print(prediction)
cat("\nAnalysis: Sales Forecast for Next Month:", round(prediction[1, "fit"], 1), "10,000 yuan\n")
cat("95% Confidence Interval: [", round(prediction[1, "lwr"], 1), ", ",
round(prediction[1, "upr"], 1), "]\n")
# 9. Residual Analysis
cat("\n=== Residual Analysis ===\n")
df <- df |>
mutate(
fitted = fitted(model3),
residual = resid(model3),
std_residual = rstandard(model3)
)
cat("Maximum Positive Residual:", round(max(df$residual), 2),
" (Sales were higher than expected)\n")
cat("Maximum Negative Residual:", round(min(df$residual), 2),
" (Sales were lower than expected)\n")
cat("Standard Deviation of Residuals:", round(sd(df$residual), 2), "\n\n")
# 10. Coefficient Visualization
coef_df <- tidy(model3, conf.int = TRUE)
print(coef_df |> select(term, estimate, std.error, p.value, conf.low, conf.high))
# 11. Actual vs Fitting a Scatter Plot
ggplot(df, aes(x = fitted, y = sales)) +
geom_point(size = 3, color = "blue") +
geom_abline(slope = 1, intercept = 0, color = "red", linetype = "dashed") +
labs(title = "Actual vs Fitting", x = "Fitted values", y = "Actual value") +
theme_minimal()
# 12. Save Model
saveRDS(model3, "sales_model.rds")
cat("\n=== The model has been saved: sales_model.rds ===\n")
النتائج المتوقعة (مقتطف):
=== Full Model: sales ~ ad + price + season + region ===
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 55.234 8.123 6.801 0.00001 ***
ad 4.876 0.234 20.838 < 2e-16 ***
price -0.432 0.123 -3.512 0.00245 **
seasonSummer 5.234 1.876 2.789 0.01234 *
seasonAutumn 2.123 1.876 1.132 0.27456
seasonWinter -3.456 1.876 -1.842 0.08345 .
regionEast China 8.234 1.876 4.389 0.00045 ***
regionSouth China 3.456 1.876 1.842 0.08345 .
regionCentral China 1.234 1.876 0.658 0.51894
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 4.234 on 15 degrees of freedom
Multiple R-squared: 0.9823, Adjusted R-squared: 0.9734
=== Forecast for Next Month ===
fit lwr upr
1 168.452 162.345 174.559
Analysis: Sales Forecast for Next Month: 168.5 10,000 yuan
95% Confidence Interval: [162.3, 174.6]
❓ أسئلة شائعة
step() ③ معايير المعلومات AIC / BIC لاختيار أبسط نموذج.📖 ملخص
- الانحدار الخطي: Y = β₀ + β₁X + ε، يتم تقديره باستخدام طريقة المربعات الصغرى العادية (OLS)
lm(y ~ x, data)صيغة المعادلة:y ~ x1 + x2متعددة المتغيرات /y ~ x1 * x2مع التفاعلات /y ~ .الكلsummary(model)6 مخرجات رئيسية: التقدير (المعامل) / الخطأ المعياري / t / Pr(>|t|) / R-squared / Fpredict(model, new, interval = "confidence" | "prediction")التوقعات- 4 رسوم بيانية تشخيصية: الفروق مقابل القيم المُقدَّرة / QQ / المقياس والموقع / الرافعة
- الانحدار المتعدد: متغيرات مستقلة متعددة؛ يتم تحويل المتغيرات الفئوية تلقائيًا إلى متغيرات وهمية
- اختيار النموذج: تعديل R² / AIC /
step()الانحدار التدريجي - المعامل: يشير β إلى أن الزيادة بمقدار وحدة واحدة في X تؤدي إلى زيادة متوسطة في Y بمقدار β (مع بقاء المتغيرات الأخرى ثابتة)
- تشير قيمة p < 0.05 إلى وجود معامل ذي دلالة إحصائية؛ وكلما ارتفع معامل R²، كان النموذج أفضل (ولكن احذر من الإفراط في الملاءمة)
📝 تمارين
-
تمرين أساسي: استخدم مجموعة البيانات المدمجة في لغة R
mtcarsلإجراءmpg ~ wtانحدار خطي بسيط، وقم بتفسير جميع النتائج باستخدامsummary()، وتوقعmpgلـwt = 3. -
أسئلة أساسية: ارسم أربعة مخططات تشخيصية للنموذج الوارد في السؤال السابق (
par(mfrow = c(2, 2)); plot(model)) للتحقق مما إذا كانت المتبقيات تتبع توزيعًا عاديًا وتتمتع بالتماثل في التباين. -
السؤال الأساسي: قم ببناء نموذج انحدار متعدد
mpg ~ wt + cyl + hpوقارن قيمتي R² و R² المعدلة بقيمتي الانحدار البسيط. أيهما أفضل؟ -
تمرين متقدم: قم بمحاكاة 100 صف من بيانات المبيعات (المبيعات مقابل الإعلانات + السعر + الموسم). أكمل العملية بأكملها: ① الاستكشاف ② النمذجة ③ التلخيص ④ التشخيص ⑤ التنبؤ ⑥ التصور. احفظ النموذج كملف RDS.
-
سؤال التحدي: استخدم
mtcarsلإجراء عملية اختيار نموذج كاملة: ① قم بتشغيل 4 نماذج (الوزن فقط / الوزن + الأسطوانة / الوزن + الأسطوانة + الحصان / الوزن + الأسطوانة + الحصان + السعة) ② قم بالمقارنة باستخدام AIC ③ استخدمstep()لإجراء الانحدار التدريجي ④ استخدمanova()لإجراء المقارنات المتداخلة ⑤ اختر أفضل نموذج وقم بعمل تنبؤ. التقط لقطات شاشة لتوثيق العملية.