Skip to content

แบบจำลองเส้นตรง (Linear Model)

ASER_banner_feature

เป้าหมาย:

สร้างแบบจำลองเส้นตรงเพื่อทดสอบความสัมพันธ์ระหว่างตัวแปรอิสระ (สาเหตุ) และ ตัวแปรตาม (ผลลัพธ์)

เตรียมข้อมูล

 code

# load datasets package
library(datasets)

# show data of Motor Trend Car Road Tests
mtcars

# show variable names in mtcars
names(mtcars)

แบบจำลองที่มีตัวแปรอิสระ 1 ตัว

  • ตัวแปรตาม (ผล) คือ ความเร็ว (mpg)
  • ตัวแปรอิสระ (เหตุ) คือ แรงม้า (hp)

 Code

# basic linear regresssion model with 1 independent variable
# dependent variable = mpg
# independent variable = hp
model1 <- lm(mpg ~ hp, data = mtcars)

# show the model results
summary(model1)
<pre>

แบบจำลองที่มีตัวแปร moderators

  • การทดสอบว่า โมเดลใหม่นั้นดีกว่าโมเดลเดินหรือไม่ให้ใช้ คำสั่ง anova(model1, model2) หาก โมเดลใหม่ดีขึ้น (Adjusted R Square เพิ่มขึ้นจริง) ค่า Pr(>F) จะต้องน้อยกว่า 0.01 (ณ ระดับ นัยสำคัญ 1%) หรือ น้อยกว่า0.05 (ณ ระดับ นัยสำคัญ 5%)

 Code

</pre>
# model1 + moderator (wt)
# colon is used to indetified the interation between hp and wt
model2 <- lm(mpg ~ hp + wt + hp:wt, data = mtcars)
summary(model2)

# compare model 1 & 2
anova(model1, model2)

# using just * will provides both linear effects and interaction effect
model3 <- lm(mpg ~ hp*wt, data = mtcars)
summary(model3)
<pre>

กลับสู่สารบัญ

9 Comments Post a comment
  1. Scott's avatar

    This blog post provides a clear explanation of how linear regression can be used to analyze relationships between variables.

    September 24, 2026

Trackbacks & Pingbacks

  1. 7 January 2014 | ubolwan540510732's Blog
  2. 7 January 2557 | irada735
  3. Test 7January 2014 | amornrat723
  4. 7 January 2014 | Sirinard Tapakhan
  5. 7 january 2014 | orachon540510724's Blog
  6. R code last class | amornrat723
  7. Linear Model | kanyapassr
  8. Linear model test | kanyapassr

Leave a comment