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>

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: