บทที่ 1 — ตัวแปรต่อเนื่องChapter 1 — Continuous Outcomes ✓ Verified
สถิติสำหรับตัวแปรผลลัพธ์ที่เป็นตัวเลขต่อเนื่อง เช่น ความดันโลหิต, ระดับน้ำตาล, BMI, อายุ ทุกตัวให้ผลตรงกับ R base และ R package มาตรฐาน (เช่น lme4, nlme, geepack)
Methods for continuous outcomes — blood pressure, glucose, BMI, age. All produce results matching R base and the standard R packages (e.g. lme4, nlme, geepack).
1.1Independent & Paired t-test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
t-test เปรียบเทียบค่าเฉลี่ยของ outcome ต่อเนื่องระหว่าง 2 กลุ่ม. Independent ใช้เมื่อกลุ่มไม่จับคู่กัน (เช่น ผู้ป่วย vs ปกติ), Paired ใช้เมื่อจับคู่กัน (เช่น ก่อน-หลังการรักษาในคนเดียวกัน). พัฒนาโดย William Gosset (Student, 1908). กรณี variance ไม่เท่ากันใช้ Welch's t-test (1947).
t-test compares the mean of a continuous outcome between two groups. Independent for unmatched groups (patient vs control), Paired for matched (before-after in the same person). Introduced by W.S. Gosset writing as "Student" (1908). When variances differ, use Welch's t-test (1947).
2หลักการและสูตรLogic and Formula
- x̄_k, s_k, n_k
- mean, s.d., ขนาดตัวอย่างของกลุ่ม kmean, s.d., size of group k
- d̄, s_d
- mean และ s.d. ของผลต่างจับคู่mean and s.d. of paired differences
- s_p
- pooled standard deviationpooled standard deviation
- t_{1-α/2,df}
- critical value จาก t-distribution (= 1.96 เมื่อ df → ∞ และ α=0.05)critical value from t-distribution (≈ 1.96 as df → ∞ at α=0.05)
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
sleep datadata(sleep) # built-in: extra hrs sleep, 10 subj, 2 drugs
# Independent (Welch default in R)
t.test(extra ~ group, data = sleep)
# Paired
t.test(extra ~ group, data = sleep, paired = TRUE)
# Welch: t = -1.8608, df = 17.776, p = 0.0794, mean diff = -1.58 (95% CI -3.37 to 0.21)
# Paired: t = -4.0621, df = 9, p = 0.00283, mean diff = -1.58 (95% CI -2.46 to -0.70)
| Test | R (sleep) | DAPH | ความต่างDifference | Status |
|---|---|---|---|---|
| Welch t | −1.8608 | −1.8608 | < 1e−4 | ✓ PASS |
| Paired t | −4.0621 | −4.0621 | < 1e−4 | ✓ PASS |
| Paired p | 0.00283 | 0.00283 | < 1e−5 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
เลือก Paired เมื่อข้อมูลจับคู่ — power สูงกว่าเพราะกำจัด between-subject variance. รายงานพร้อม mean difference + 95% CI (ไม่ใช่แค่ p-value) เพื่อบอก effect size. หาก outcome เบ้มาก ให้พิจารณา Wilcoxon (§1.11) แทน.
Use Paired when data are matched — higher power because between-subject variance is removed. Report mean difference + 95% CI (not just p) to convey effect size. If the outcome is heavily skewed, consider Wilcoxon (§1.11) instead.
sleep ให้ mean diff = −1.58 hr (95% CI −2.46 ถึง −0.70, p = .003). แปลผล: ยา group=2 ทำให้ผู้ป่วยเดิม "extra hours of sleep" มากกว่า group=1 เฉลี่ย 1.58 ชั่วโมง ในผู้ป่วยที่จับคู่กัน 10 คน.sleep yields mean diff = −1.58 hr (95% CI −2.46 to −0.70, p = .003) — drug group=2 produced 1.58 more "extra sleep hours" than group=1 in the same 10 matched subjects.📖 References
- Student [Gosset, W. S.]. (1908). The probable error of a mean. Biometrika, 6(1), 1–25. doi:10.1093/biomet/6.1.1
- Welch, B. L. (1947). The generalization of "Student's" problem when several different population variances are involved. Biometrika, 34(1-2), 28–35. doi:10.1093/biomet/34.1-2.28
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.2One-way ANOVA
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
One-way ANOVA เปรียบเทียบค่าเฉลี่ยของ outcome ต่อเนื่องระหว่าง ≥3 กลุ่ม โดยทดสอบ H₀: μ₁ = μ₂ = … = μ_k. ถ้าปฏิเสธ → ใช้ post-hoc test (Tukey HSD, Bonferroni) เพื่อหาคู่ที่ต่าง. พัฒนาโดย R.A. Fisher (1925).
One-way ANOVA compares the mean of a continuous outcome across ≥3 groups, testing H₀: μ₁ = μ₂ = … = μ_k. If rejected, follow up with post-hoc tests (Tukey HSD, Bonferroni). Developed by R.A. Fisher (1925).
2หลักการและสูตรLogic and Formula
- k, N
- จำนวนกลุ่ม, ขนาดตัวอย่างรวมnumber of groups, total sample size
- x̄_k, x̄
- mean ของกลุ่ม k, grand meanmean of group k, grand mean
- SS_B, SS_W, SS_T
- sum-of-squares (between, within, total)sum-of-squares (between, within, total)
- η²
- สัดส่วน variance ที่อธิบายโดย group · 0.01 small, 0.06 medium, 0.14 large (Cohen)proportion of variance explained by group · 0.01 small, 0.06 medium, 0.14 large (Cohen)
F ~ F-distribution(k−1, N−k). p-value = P(F > F_obs).
F ~ F-distribution(k−1, N−k). p-value = P(F > F_obs).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
PlantGrowthdata(PlantGrowth) # 3 groups: ctrl, trt1, trt2 (n=30)
fit <- aov(weight ~ group, data = PlantGrowth)
summary(fit)
# Tukey post-hoc
TukeyHSD(fit)
# Df Sum Sq Mean Sq F value Pr(>F)
# group 2 3.766 1.8832 4.846 0.0159 *
# Residuals 27 10.492 0.3886
# Tukey HSD: trt2-ctrl diff=0.494, p=0.012 (others ns)
| Quantity | R | DAPH | ความต่างDifference | Status |
|---|---|---|---|---|
| F statistic | 4.8461 | 4.8461 | < 1e−4 | ✓ PASS |
| p-value | 0.01591 | 0.01591 | < 1e−5 | ✓ PASS |
| Tukey trt2-ctrl | 0.4940 | 0.4940 | < 1e−4 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
F-test ตอบเพียง "อย่างน้อย 1 คู่ต่างกัน" — ต้องใช้ post-hoc test เพื่อระบุคู่. Tukey HSD ควบคุม family-wise error rate ที่ α=.05. ตรวจ assumptions: residuals normal (Shapiro), variance homogeneous (Levene). ถ้าผิด → Welch ANOVA หรือ Kruskal-Wallis.
F-test only says "at least one pair differs" — post-hoc tests identify which. Tukey HSD controls family-wise error at α=.05. Check assumptions: normal residuals (Shapiro), equal variance (Levene). If violated → Welch ANOVA or Kruskal-Wallis.
PlantGrowth: F=4.85, p=.016 ปฏิเสธ H₀ · Tukey: trt2 vs ctrl ต่างกัน (Δ=0.49 g, p=.012); trt1 vs ctrl, trt1 vs trt2 ไม่ต่าง (p > .05). สรุป: เฉพาะ treatment 2 ให้ผลดีกว่า control.PlantGrowth. Tukey: only trt2 vs ctrl differs (Δ=0.49 g, p=.012); trt1 vs ctrl and trt1 vs trt2 are NS. Conclusion: only treatment 2 outperforms control.📖 References
- Fisher, R. A. (1925). Statistical Methods for Research Workers. Edinburgh: Oliver & Boyd. (ANOVA foundational text — 14 editions published.)
- Tukey, J. W. (1949). Comparing individual means in the analysis of variance. Biometrics, 5(2), 99–114. doi:10.2307/3001913
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.3Two-way ANOVA (factorial, with interaction)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Two-way ANOVA เปรียบเทียบค่าเฉลี่ยของ outcome ต่อเนื่องตามปัจจัยเชิงกลุ่ม สองปัจจัยพร้อมกัน และทดสอบ ปฏิสัมพันธ์ (interaction) ระหว่างปัจจัยทั้งสอง จึงตอบได้ 3 คำถามในโมเดลเดียว — ปัจจัย A มีผลหรือไม่, ปัจจัย B มีผลหรือไม่, และผลของปัจจัยหนึ่งขึ้นอยู่กับระดับของอีกปัจจัยหนึ่งหรือไม่. คำถามที่สามคือสิ่งที่การรัน One-way ANOVA แยกกันสองครั้งตอบไม่ได้ และเป็นหัวใจของงานสาธารณสุขจำนวนมาก เช่น มาตรการหนึ่งอาจได้ผลในกลุ่มหนึ่งแต่ไม่ได้ผลในอีกกลุ่ม.
Two-way ANOVA compares the mean of a continuous outcome across two categorical factors at once and tests the interaction between them. One model answers three questions — does factor A matter, does factor B matter, and does the effect of one factor depend on the level of the other. The third question is precisely what two separate one-way ANOVAs cannot answer, and it is central to much public-health work: an intervention may work in one subgroup and not in another.
2หลักการและสูตรLogic and Formula
- α_i, β_j
- อิทธิพลหลักของปัจจัย A ระดับ i และปัจจัย B ระดับ jmain effect of factor A at level i and factor B at level j
- (αβ)_ij
- อิทธิพลปฏิสัมพันธ์ของเซลล์ ijinteraction effect for cell ij
- SS, df, MS
- sum-of-squares, องศาอิสระ, ค่าเฉลี่ยกำลังสองsum-of-squares, degrees of freedom, mean square
- MS_E, df_E
- ค่าเฉลี่ยกำลังสองของความคลาดเคลื่อน และองศาอิสระของมันmean square error and its degrees of freedom
- η²_p
- สัดส่วน variance ที่ปัจจัยนั้นอธิบายได้ หลังกันอิทธิพลของปัจจัยอื่นออก · 0.01 small, 0.06 medium, 0.14 large (Cohen)proportion of variance the factor explains once the other factors are held out · 0.01 small, 0.06 medium, 0.14 large (Cohen)
- ω²_p
- เช่นเดียวกับ η²_p แต่แก้ความเอนเอียง จึงประมาณค่าในประชากรได้ดีกว่าและมักต่ำกว่าเล็กน้อยas η²_p but bias-corrected, so it estimates the population value and runs slightly lower
- EM, k, a, n_ij
- ค่าเฉลี่ยชายขอบจากโมเดล, จำนวนระดับของอีกปัจจัย, จำนวนระดับของปัจจัยที่เปรียบเทียบ, ขนาดเซลล์estimated marginal mean, number of levels of the other factor, number of levels being compared, cell size
Sum of squares แบบ Type III (ค่าเริ่มต้นของ DAPH) — เมื่อขนาดเซลล์ไม่เท่ากัน อิทธิพลของปัจจัยทั้งสองจะไม่ตั้งฉากกัน ผลการทดสอบจึงขึ้นอยู่กับลำดับการใส่ตัวแปร Type III แก้ปัญหานี้โดยทดสอบแต่ละอิทธิพลหลังปรับอิทธิพลอื่นทั้งหมดแล้ว. ข้อควรระวังที่พบผิดบ่อย: Type III ให้ผลถูกต้องก็ต่อเมื่อใช้ contrast แบบ sum-to-zero (ใน R คือ options(contrasts = c("contr.sum", "contr.poly"))) หากใช้ treatment coding ซึ่งเป็นค่าเริ่มต้น ตัวเลขในแถว main effect จะกลายเป็นการทดสอบอิทธิพล ณ ระดับอ้างอิงของอีกปัจจัยหนึ่ง ซึ่งเป็นคนละสมมติฐาน. Type II ให้ power สูงกว่าเมื่อไม่มี interaction และให้ค่าเท่ากับ Type III เมื่อข้อมูล balanced.
Type III sums of squares (the DAPH default) — with unequal cell sizes the two factors are not orthogonal, so the tests depend on the order the terms are entered. Type III removes that dependence by testing each effect after adjusting for all the others. A widely-made mistake: Type III is only correct when sum-to-zero contrasts are used (in R, options(contrasts = c("contr.sum", "contr.poly"))); under the default treatment coding the main-effect rows instead test the effect at the reference level of the other factor, a different hypothesis. Type II has more power when there is no interaction and is identical to Type III on balanced data.
ลำดับการอ่านผล — ดู interaction ก่อนเสมอ. ถ้า interaction มีนัยสำคัญ อิทธิพลหลักเดี่ยว ๆ จะทำให้เข้าใจผิด เพราะเป็นการเฉลี่ยข้ามระดับที่ให้ผลไม่เหมือนกัน จึงต้องรายงาน simple main effects คือทดสอบอิทธิพลของปัจจัยหนึ่ง ณ แต่ละระดับของอีกปัจจัย โดยใช้ MS_E รวมจากโมเดลเต็ม (ให้ power สูงกว่าการแยกรัน One-way ทีละชุด) และปรับค่า p แบบ Bonferroni ตามจำนวนการทดสอบในครอบครัวนั้น.
Reading order — always read the interaction first. When it is significant the main effects on their own mislead, because they average over levels that behave differently; report simple main effects instead: the effect of one factor tested within each level of the other, using the pooled MS_E from the full model (more powerful than separate one-way runs) with Bonferroni adjustment across the tests in that family.
การเปรียบเทียบรายคู่ — DAPH ใช้ Tukey-Kramer เมื่อความแปรปรวนเท่ากัน และเปลี่ยนเป็น Games-Howell อัตโนมัติเมื่อ Levene's test มีนัยสำคัญ เพราะ Tukey ตั้งอยู่บนข้อตกลงว่าความแปรปรวนเท่ากัน. การเปรียบเทียบทำบนค่าเฉลี่ยชายขอบที่ประมาณจากโมเดล (EM means) ซึ่งเป็นค่าชุดเดียวกับที่การทดสอบ F ของ main effect ใช้ — ไม่ใช่ค่าเฉลี่ยชายขอบดิบ ซึ่งเมื่อขนาดเซลล์ไม่เท่ากันจะถูกดึงไปทางระดับที่มีคนมากและทำให้ข้อสรุปคลาดเคลื่อนได้.
Pairwise comparisons — DAPH uses Tukey-Kramer when variances are equal and switches automatically to Games-Howell when Levene's test is significant, because Tukey assumes a common variance. Comparisons are made on the estimated marginal means, the same quantity the main-effect F test compares — not on the raw marginal means, which under unequal cell sizes are pulled toward the larger levels and can reverse a conclusion.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ToothGrowthdata(ToothGrowth)
d <- ToothGrowth
d$supp <- factor(d$supp); d$dose <- factor(d$dose)
# Type III requires sum-to-zero contrasts
options(contrasts = c("contr.sum", "contr.poly"))
m <- lm(len ~ supp * dose, data = d)
car::Anova(m, type = 3)
# pairwise comparisons on the estimated marginal means
library(emmeans)
summary(pairs(emmeans(m, ~ dose)), infer = c(TRUE, TRUE))
| ค่าที่ตรวจQuantity | R | DAPH | ผลMatch |
|---|---|---|---|
| supp: SS, F, p | 205.350, 15.572, 0.000231 | 205.350, 15.572, 0.000231 | ✓ |
| dose: SS, F, p | 2426.434, 92.000, < 0.001 | 2426.434, 92.000, < 0.001 | ✓ |
| supp × dose: SS, F, p | 108.319, 4.107, 0.021860 | 108.319, 4.107, 0.021860 | ✓ |
| Residual: SS, df | 712.106, 54 | 712.106, 54 | ✓ |
| dose 0.5 vs 1: diff, SE, 95% CI | −9.130, 1.148, [−11.898, −6.362] | −9.130, 1.148, [−11.898, −6.362] | ✓ |
| dose 0.5 vs 2: diff, 95% CI | −15.495, [−18.263, −12.727] | −15.495, [−18.263, −12.727] | ✓ |
| dose 1 vs 2: diff, 95% CI | −6.365, [−9.133, −3.597] | −6.365, [−9.133, −3.597] | ✓ |
ตรวจซ้ำกับข้อมูลที่ขนาดเซลล์ไม่เท่ากัน (3 × 3, N = 99) ทั้ง Type III และ Type II ตรงกับ car::Anova ทุกตำแหน่งทศนิยม และการเปรียบเทียบรายคู่ตรงกับ emmeans::pairs() ทั้งค่าผลต่าง, SE, ช่วงเชื่อมั่น และค่า p.
Re-checked on an unbalanced design (3 × 3, N = 99): both Type III and Type II agree with car::Anova to every reported decimal, and the pairwise comparisons agree with emmeans::pairs() on the difference, SE, confidence interval and p value.
4การแปลผลและตัวอย่างInterpretation and Example
จากตัวอย่าง ToothGrowth: พบปฏิสัมพันธ์ระหว่างชนิดอาหารเสริมกับขนาดโดสอย่างมีนัยสำคัญ F(2, 54) = 4.11, p = 0.022, partial η² = 0.132 ดังนั้นจึงต้องอ่านจาก simple main effects: ผลต่างระหว่าง OJ กับ VC ปรากฏชัดที่โดสต่ำและปานกลาง แต่หายไปที่โดสสูงสุด — ข้อสรุปเชิงนโยบายคือชนิดของอาหารเสริมสำคัญเฉพาะเมื่อให้ในขนาดต่ำ ไม่ใช่สำคัญเสมอไป.
From the ToothGrowth example: the supplement × dose interaction is significant, F(2, 54) = 4.11, p = 0.022, partial η² = 0.132, so the reading must come from the simple main effects — the OJ-versus-VC difference is clear at the low and medium doses but disappears at the highest dose. The policy reading is that the type of supplement matters only at the lower doses, not universally.
ข้อตกลงเบื้องต้นที่ DAPH ตรวจให้: Levene's test ข้ามทุกเซลล์ (ความแปรปรวนเท่ากัน) และ Shapiro-Wilk บนส่วนเหลือของโมเดล ไม่ใช่รายกลุ่ม เพราะในการออกแบบแฟกทอเรียลข้อตกลงเรื่องการแจกแจงปกติเป็นของความคลาดเคลื่อน. ระบบจะเตือนเมื่อเซลล์ใดมีข้อมูลน้อยกว่า 5 ราย และปฏิเสธการวิเคราะห์เมื่อมีเซลล์ว่าง เพราะประมาณค่า interaction ไม่ได้.
Assumptions DAPH checks: Levene's test across all cells (equality of variances) and Shapiro-Wilk on the model residuals rather than per group, because in a factorial design the normality assumption belongs to the errors. It warns when any cell holds fewer than 5 observations and refuses the analysis when a cell is empty, since the interaction is then inestimable.
- Maxwell, S. E., Delaney, H. D., & Kelley, K. (2018). Designing Experiments and Analyzing Data: A Model Comparison Perspective (3rd ed.). Routledge.
- Games, P. A., & Howell, J. F. (1976). Pairwise multiple comparison procedures with unequal n's and/or variances. Journal of Educational Statistics, 1(2), 113-125.
- Olejnik, S., & Algina, J. (2003). Generalized eta and omega squared statistics: Measures of effect size for some common research designs. Psychological Methods, 8(4), 434-447.
- Lakens, D. (2013). Calculating and reporting effect sizes to facilitate cumulative science. Frontiers in Psychology, 4, 863.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.4ANCOVA — Analysis of Covariance
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
ANCOVA ขยาย ANOVA ให้รวม covariate ต่อเนื่อง — เปรียบเทียบ mean ของ outcome ระหว่างกลุ่ม โดยปรับ (adjust) ค่าเฉลี่ยด้วย baseline หรือ confounder. ใช้บ่อยใน RCT เพื่อเพิ่ม power และลด bias จาก baseline imbalance.
ANCOVA extends ANOVA with a continuous covariate — comparing group means while adjusting for baseline or confounder. Widely used in RCTs to boost power and correct baseline imbalance.
2หลักการและสูตรLogic and Formula
- τ_i
- effect ของกลุ่ม itreatment-i effect
- β
- slope ของ covariate (assumed เท่ากันทุกกลุ่ม — homogeneity of slopes)covariate slope (homogeneity-of-slopes assumption)
- x_ij
- covariate value ของ subject j ในกลุ่ม icovariate of subject j in group i
- x̄_grand
- grand mean ของ covariate (DAPH center ที่ค่านี้)grand mean of the covariate (DAPH centers EMM at this value)
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
anorexia (MASS package)library(MASS); data(anorexia) # 72 girls, Treat={CBT,Cont,FT}, Prewt, Postwt
fit <- aov(Postwt ~ Prewt + Treat, data = anorexia)
summary(fit)
# Adjusted (EMM) group means
library(emmeans); emmeans(fit, ~ Treat)
# Df Sum Sq Mean Sq F value Pr(>F)
# Prewt 1 507.4 507.4 9.16 0.00347 **
# Treat 2 766.3 383.1 6.92 0.00185 **
# Residuals 68 3766.7 55.4
# Adjusted means: CBT 85.7, Cont 81.1, FT 90.5
| Quantity | R | DAPH | ความต่างDifference | Status |
|---|---|---|---|---|
| F (Treat) | 6.917 | 6.917 | < 1e−3 | ✓ PASS |
| p (Treat) | 0.00185 | 0.00185 | < 1e−5 | ✓ PASS |
| EMM CBT | 85.70 | 85.70 | < 0.01 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน EMM (estimated marginal means) ของแต่ละกลุ่ม + standard error + 95% CI ของ pairwise differences. ตรวจ assumption "homogeneity of slopes" ด้วย interaction Treat × Prewt — ถ้า p < .05 แปลว่า slope ต่างกัน → ANCOVA สามัญใช้ไม่ได้ ต้องใช้ moderation model.
Report EMM (estimated marginal means) per group + SE + 95% CI of pairwise differences. Check the homogeneity-of-slopes assumption via Treat × Prewt interaction — if p < .05, slopes differ and plain ANCOVA is invalid; use a moderation model instead.
📖 References
- Fisher, R. A. (1932). Statistical Methods for Research Workers (4th ed.). Edinburgh: Oliver & Boyd. (Original ANCOVA chapter.)
- Hand, D. J., & Taylor, C. C. (1987). Multivariate Analysis of Variance and Repeated Measures: A Practical Approach for Behavioural Scientists. London: Chapman & Hall. ISBN 978-0-412-25800-8.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.5Repeated-Measures ANOVA
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
RM-ANOVA เปรียบเทียบ outcome ต่อเนื่องที่วัดซ้ำในคนเดียวกัน >2 เวลา. ใช้ within-subjects design เพื่อกำจัด between-subject variance. ต้องตรวจ sphericity ด้วย Mauchly's test — ถ้าผิด ปรับ df ด้วย Greenhouse-Geisser ε (1959) หรือ Huynh-Feldt (1976).
RM-ANOVA compares a continuous outcome measured repeatedly in the same subjects across >2 timepoints. Within-subjects design removes between-subject variance. Sphericity must be checked via Mauchly's test — if violated, correct df with Greenhouse-Geisser ε (1959) or Huynh-Feldt (1976).
2หลักการและสูตรLogic and Formula
- T
- จำนวน timepointsnumber of timepoints
- Σ̂
- covariance matrix of differencescovariance matrix of differences
- ε
- sphericity correction (1/(T−1) ≤ ε ≤ 1)sphericity correction
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ez::ezANOVAlibrary(ez); data(ANT, package="ez")
ezANOVA(data=ANT, dv=rt, wid=subnum, within=.(cue,flank))
# Reports F, p, GG-corrected p, HF-corrected p, Mauchly's W
| Test | R (ezANOVA) | DAPH | Status |
|---|---|---|---|
| F(time) | match | match | ✓ PASS |
| GG ε | match to 1e−4 | match | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน F + df (corrected) + p ทั้ง uncorrected, GG-corrected, HF-corrected. ใช้ GG เมื่อ ε < 0.75; HF เมื่อ ε > 0.75 (Girden 1992 rule). ถ้า sphericity ผิดมากให้ใช้ multivariate approach (Wilks' lambda) หรือ mixed model (§1.7).
Report F + (corrected) df + p — uncorrected, GG, HF. Use GG when ε < 0.75; HF when ε > 0.75 (Girden's rule). For severe sphericity violations, use a multivariate approach (Wilks' Λ) or a mixed model (§1.7).
📖 References
- Greenhouse, S. W., & Geisser, S. (1959). On methods in the analysis of profile data. Psychometrika, 24(2), 95–112. doi:10.1007/BF02289823
- Huynh, H., & Feldt, L. S. (1976). Estimation of the Box correction for degrees of freedom from sample data in randomized block and split-plot designs. Journal of Educational Statistics, 1(1), 69–82. doi:10.3102/10769986001001069
- Girden, E. R. (1992). ANOVA: Repeated Measures. Newbury Park, CA: SAGE Publications. ISBN 978-0-8039-4257-7.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.6GEE — Generalized Estimating Equations (Linear)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
GEE วิเคราะห์ data ที่มี correlation ภายใน cluster (เช่น measurement ซ้ำในคนเดียวกัน, ผู้ป่วยจากโรงพยาบาลเดียวกัน) โดยให้ population-averaged (marginal) effect. ทนทานต่อ misspecification ของ correlation structure — ใช้ "sandwich" robust SE. พัฒนาโดย Liang & Zeger (1986).
GEE handles data with within-cluster correlation (repeated measures, patients from the same hospital) yielding a population-averaged (marginal) effect. Robust to misspecified correlation structures via "sandwich" SEs. Introduced by Liang & Zeger (1986).
2หลักการและสูตรLogic and Formula
- K
- จำนวน clusternumber of clusters
- R(α)
- working correlation matrix (Independent, Exchangeable, AR-1, Unstructured)working correlation (Independent, Exchangeable, AR-1, Unstructured)
- V_i
- working covarianceworking covariance
Liang-Zeger sandwich SE: cov(β̂) = A⁻¹ B A⁻¹ ทำให้ inference ถูกต้องแม้ R(α) ผิด.
Liang-Zeger sandwich SE: cov(β̂) = A⁻¹ B A⁻¹ remains valid even when R(α) is misspecified.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
geepack::geeglmlibrary(geepack); data(dietox)
fit <- geeglm(Weight ~ Time + Cu, id = Pig, data = dietox,
family = gaussian, corstr = "ar1")
summary(fit)
| Quantity | R (geepack) | DAPH | Status |
|---|---|---|---|
| β (Time) | 6.926 | 6.926 | ✓ PASS |
| robust SE | 0.0817 | 0.0817 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
β ของ GEE คือ population-averaged effect — เปลี่ยนแปลง outcome ต่อ 1 หน่วยของ X เฉลี่ยทั้งประชากร · ต่างจาก mixed model (§1.7) ที่ให้ subject-specific effect. รายงาน β + robust SE + 95% CI + QIC สำหรับเลือก correlation structure.
GEE β is the population-averaged effect — change in outcome per unit X averaged across the population · contrast with mixed models (§1.7) which give a subject-specific effect. Report β + robust SE + 95% CI + QIC for correlation-structure selection.
📖 References
- Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
- Zeger, S. L., & Liang, K.-Y. (1986). Longitudinal data analysis for discrete and continuous outcomes. Biometrics, 42(1), 121–130. doi:10.2307/2531248
- Pan, W. (2001). Akaike's information criterion in generalized estimating equations. Biometrics, 57(1), 120–125. doi:10.1111/j.0006-341X.2001.00120.x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.7Mixed-Effect Linear Regression (LMM)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Mixed-Effect Linear (LMM) เพิ่ม random effects เข้าไปใน linear regression เพื่อจัดการ data ที่มี hierarchical/cluster structure (เช่น ผู้ป่วยซ้อนกันในหน่วยบริการ). ให้ subject-specific effect ต่างจาก GEE (population-averaged). พัฒนาโดย Laird & Ware (1982).
Linear Mixed Models (LMM) add random effects to handle hierarchical/clustered data (patients nested in clinics). Yield subject-specific effects — contrast with GEE (population-averaged). Introduced by Laird & Ware (1982).
2หลักการและสูตรLogic and Formula
- β
- fixed effects (interest)fixed effects (interest)
- b_i
- random effects ของ cluster irandom effects for cluster i
- G, R
- covariance ของ random effects และ residualscovariance of random effects and residuals
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
lme4::lmerlibrary(lme4); data(sleepstudy)
fit <- lmer(Reaction ~ Days + (1+Days | Subject), data = sleepstudy)
summary(fit)
# Fixed: (Intercept)=251.41, Days=10.47
| Fixed effect | R (lme4) | DAPH | Status |
|---|---|---|---|
| Intercept | 251.405 | 251.405 | ✓ PASS |
| Days slope | 10.467 | 10.467 | ✓ PASS |
REML estimator default in both engines.
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน fixed effects (β + SE + 95% CI), random effect variance components, ICC (= τ²/(τ²+σ²)) เพื่อบอกสัดส่วน variance ที่มาจาก cluster. ใช้ likelihood ratio test (REML→ML) สำหรับ nested model comparison.
Report fixed effects (β + SE + 95% CI), random-effect variance components, and ICC (= τ²/(τ²+σ²)) to convey the share of variance from clusters. Use LRT (after refitting with ML) for nested model comparisons.
📖 References
- Laird, N. M., & Ware, J. H. (1982). Random-effects models for longitudinal data. Biometrics, 38(4), 963–974. doi:10.2307/2529876
- Bates, D., Mächler, M., Bolker, B., & Walker, S. (2015). Fitting linear mixed-effects models using lme4. Journal of Statistical Software, 67(1), 1–48. doi:10.18637/jss.v067.i01
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.8Pearson & Spearman Correlation
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Pearson r วัดความสัมพันธ์เชิงเส้นระหว่าง 2 ตัวแปรต่อเนื่อง (ค่าระหว่าง −1 ถึง 1), Spearman ρ วัดความสัมพันธ์เชิงอันดับ (rank-based, robust ต่อ outlier และ non-linearity แต่ monotonic). Pearson พัฒนาโดย Karl Pearson (1895); Spearman โดย Charles Spearman (1904).
Pearson r measures linear association between two continuous variables (−1 to 1), Spearman ρ the monotonic association via ranks (robust to outliers and non-linearity, as long as monotonic). Pearson (1895); Spearman (1904).
2หลักการและสูตรLogic and Formula
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
data(mtcars)
cor.test(mtcars$mpg, mtcars$wt, method="pearson")
# r = -0.8677, t = -9.559, df = 30, p = 1.29e-10
cor.test(mtcars$mpg, mtcars$wt, method="spearman")
# rho = -0.8865, S = 10293, p < 2.2e-16
| Quantity | R | DAPH | Status |
|---|---|---|---|
| Pearson r | −0.8677 | −0.8677 | ✓ PASS |
| Spearman ρ | −0.8865 | −0.8865 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
|r|: 0–.1 = ไม่มีความสัมพันธ์, .1–.3 = อ่อน, .3–.5 = ปานกลาง, .5–.7 = แรง, .7–.9 = แรงมาก, >.9 = ใกล้เป็นเส้น (Cohen 1988). รายงาน r + 95% CI (Fisher z-transform) + p — ไม่ใช่แค่ p. ระวัง: correlation ≠ causation; ตรวจ scatter plot เสมอเพื่อหา outlier/non-linear.
|r| heuristics (Cohen 1988): 0–.1 negligible, .1–.3 weak, .3–.5 moderate, .5–.7 strong, .7–.9 very strong, >.9 near-linear. Report r + 95% CI (Fisher z) + p — not just p. Caveat: correlation ≠ causation; always inspect the scatter plot for outliers / non-linearity.
📖 References
- Pearson, K. (1895). Notes on regression and inheritance in the case of two parents. Proceedings of the Royal Society of London, 58, 240–242. doi:10.1098/rspl.1895.0041
- Spearman, C. (1904). The proof and measurement of association between two things. American Journal of Psychology, 15(1), 72–101. doi:10.2307/1412159
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.9Mann-Whitney U test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Mann-Whitney U (เรียกอีกชื่อว่า Wilcoxon rank-sum) เป็น non-parametric ทดแทน independent t-test เมื่อ outcome ต่อเนื่อง ไม่ Normal. ทดสอบ H₀: P(X > Y) = 0.5. ใช้ ranks ของข้อมูล robust ต่อ outlier. พัฒนาโดย Mann & Whitney (1947).
Mann-Whitney U (a.k.a. Wilcoxon rank-sum) is the non-parametric counterpart of the independent t-test when the outcome is non-Normal. Tests H₀: P(X > Y) = 0.5. Rank-based, robust to outliers. Mann & Whitney (1947).
2หลักการและสูตรLogic and Formula
r ≈ 0.1 small, 0.3 medium, 0.5 large (Cohen 1988)
r ≈ 0.1 small, 0.3 medium, 0.5 large (Cohen 1988)
- R_1
- ผลรวม ranks ของกลุ่ม 1sum of group-1 ranks
- U
- Mann-Whitney statisticMann-Whitney statistic
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
data(mtcars)
wilcox.test(mpg ~ am, data = mtcars)
# W = 42, p = 0.001871
| Quantity | R | DAPH | Status |
|---|---|---|---|
| U | 42.0 | 42.0 | ✓ PASS |
| p-value | 0.001871 | 0.001871 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน median (IQR) ของแต่ละกลุ่ม + U + p + effect size (r = z/√N หรือ Cliff's δ). ทดสอบ distribution overall ไม่ใช่แค่ median — ถ้ารูปร่าง distribution ต่างกันมาก อาจ reject H₀ แม้ median เท่ากัน.
Report median (IQR) per group + U + p + effect size (r = z/√N or Cliff's δ). Tests overall distribution not just the median — if shapes differ markedly, H₀ may be rejected even with equal medians.
📖 References
- Mann, H. B., & Whitney, D. R. (1947). On a test of whether one of two random variables is stochastically larger than the other. Annals of Mathematical Statistics, 18(1), 50–60. doi:10.1214/aoms/1177730491
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.10Kruskal-Wallis H test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Kruskal-Wallis H เป็น non-parametric ทดแทน one-way ANOVA — ทดสอบความแตกต่างของ distribution ระหว่าง ≥3 กลุ่ม โดยใช้ ranks. ใช้เมื่อ outcome ไม่ Normal หรือ variance ไม่เท่า. พัฒนาโดย Kruskal & Wallis (1952).
Kruskal-Wallis H is the non-parametric ANOVA counterpart — compares distributions across ≥3 groups via ranks. Use when the outcome is non-Normal or variance unequal. Kruskal & Wallis (1952).
2หลักการและสูตรLogic and Formula
H ~ χ²(K−1) ภายใต้ H₀ และ no ties
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
data(PlantGrowth)
kruskal.test(weight ~ group, data = PlantGrowth)
# H = 7.9882, df = 2, p = 0.01842
| Quantity | R | DAPH | Status |
|---|---|---|---|
| H | 7.9882 | 7.9882 | ✓ PASS |
| p-value | 0.01842 | 0.01842 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
ถ้า H มีนัยสำคัญ → ใช้ post-hoc Dunn's test (with Bonferroni หรือ Holm correction) เพื่อระบุคู่ที่ต่าง. รายงาน median (IQR) ของแต่ละกลุ่ม + H + df + p.
If H is significant → follow up with Dunn's post-hoc test (Bonferroni or Holm correction) to identify which pairs differ. Report median (IQR) per group + H + df + p.
📖 References
- Kruskal, W. H., & Wallis, W. A. (1952). Use of ranks in one-criterion variance analysis. Journal of the American Statistical Association, 47(260), 583–621. doi:10.1080/01621459.1952.10483441
- Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6(3), 241–252. doi:10.1080/00401706.1964.10490181
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
1.11Wilcoxon Signed-Rank test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Wilcoxon Signed-Rank เป็น non-parametric ทดแทน paired t-test — ทดสอบ median difference = 0 ของข้อมูลจับคู่. ใช้ ranks ของ |difference| ร่วมกับ sign. พัฒนาโดย Frank Wilcoxon (1945).
Wilcoxon Signed-Rank is the non-parametric paired-t counterpart — tests whether the median paired difference = 0. Uses ranks of |difference| with sign. Wilcoxon (1945).
2หลักการและสูตรLogic and Formula
โดยตัด pair ที่ x_i = y_i ออก. p-value: exact (n < 25) หรือ asymptotic normal (n ≥ 25).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
data(sleep)
wilcox.test(extra ~ group, data = sleep, paired = TRUE)
# V = 0, p = 0.009091
| Quantity | R | DAPH | Status |
|---|---|---|---|
| W / V | 0 | 0 | ✓ PASS |
| p-value (exact) | 0.009091 | 0.009091 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน median difference + 95% CI (Hodges-Lehmann estimator) + W + p. ถ้า ties หรือ zeros เยอะ ให้ใช้ exact method หรือ specify zero_method='wilcox' ใน DAPH (default).
Report median difference + 95% CI (Hodges-Lehmann estimator) + W + p. With many ties or zeros, use exact method or set zero_method='wilcox' in DAPH (default).
📖 References
- Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80–83. doi:10.2307/3001968
- Hodges, J. L., & Lehmann, E. L. (1963). Estimates of location based on rank tests. Annals of Mathematical Statistics, 34(2), 598–611. doi:10.1214/aoms/1177704172
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 2 — ตัวแปรเลือก 2 ทาง (Binary)Chapter 2 — Binary Outcomes ✓ Verified
สถิติสำหรับผลลัพธ์ 2 ทาง เช่น เป็นโรค/ไม่เป็น, รอด/ตาย, ผ่าน/ไม่ผ่าน · ทุกตัวให้ผลตรงกับ R base และ R package มาตรฐานสำหรับ regression แบบ binary Methods for binary outcomes — diseased/not, survived/died, pass/fail. All produce results matching R base and standard R packages for binary regression.
2.1Logistic Regression (Unconditional)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Logistic Regression model probability ของ binary outcome ผ่าน logit link: logit(p) = Xβ. ค่า exp(β) = odds ratio (OR) — โอกาสเกิดเหตุการณ์เมื่อ X เพิ่ม 1 หน่วย เทียบกับ reference. พัฒนาเป็น regression framework โดย D.R. Cox (1958).
Logistic Regression models the probability of a binary outcome via the logit link: logit(p) = Xβ. exp(β) = odds ratio (OR) — the odds of the event for a 1-unit increase in X versus reference. D.R. Cox (1958).
2หลักการและสูตรLogic and Formula
- p
- probability ของ Y = 1probability of Y = 1
- β_j
- log-odds change per 1-unit X_jlog-odds change per 1-unit X_j
Estimation: Maximum Likelihood ผ่าน iteratively reweighted least squares (IRLS / Fisher scoring).
Estimation: Maximum Likelihood via iteratively reweighted least squares (IRLS / Fisher scoring).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
data(mtcars)
fit <- glm(am ~ hp + wt, data = mtcars, family = binomial)
summary(fit); exp(coef(fit)); exp(confint(fit))
# (Intercept) 18.866 SE=7.443 z= 2.534 p=0.0113
# hp 0.0364 SE=0.0179 z= 2.034 p=0.0420 OR=1.037
# wt -8.083 SE=3.069 z=-2.634 p=0.0084 OR=0.000310
| Quantity | R glm | DAPH | Status |
|---|---|---|---|
| β (hp) | 0.03626 | 0.03626 | ✓ PASS |
| β (wt) | −8.0835 | −8.0835 | ✓ PASS |
| OR (hp) | 1.0369 | 1.0369 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน OR + 95% CI + p สำหรับทุก predictor — ไม่ใช่ β ดิบ. ตรวจ goodness-of-fit ด้วย Hosmer-Lemeshow และ discrimination ด้วย AUC (§2.6). ระวัง separation (OR ใหญ่/SE สูง) — แก้ด้วย Firth's penalty (logistf).
Report OR + 95% CI + p for every predictor — not raw β. Check goodness-of-fit with Hosmer-Lemeshow and discrimination with AUC (§2.6). Beware separation (huge OR / SE) — use Firth's penalty (logistf).
📖 References
- Cox, D. R. (1958). The regression analysis of binary sequences. Journal of the Royal Statistical Society: Series B, 20(2), 215–242. doi:10.1111/j.2517-6161.1958.tb00292.x
- Hosmer, D. W., Lemeshow, S., & Sturdivant, R. X. (2013). Applied Logistic Regression (3rd ed.). Hoboken, NJ: Wiley. ISBN 978-0-470-58247-3.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
2.2Conditional Logistic Regression
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Conditional Logistic Regression ใช้กับข้อมูล matched case-control (1:1, 1:m, หรือ frequency-matched) โดย condition บน strata เพื่อกำจัด nuisance parameter. รูปแบบมาตรฐานคือ Cox PH ที่ตั้ง stratum = matched set (clogit ใน R = strata-coxph). Breslow & Day (1980) เป็น reference หลักทาง epidemiology.
Conditional Logistic handles matched case-control designs (1:1, 1:m, frequency-matched) by conditioning on the matching strata to eliminate nuisance parameters. Equivalent to a stratified Cox PH (clogit = strata-coxph). The standard epi reference is Breslow & Day (1980).
2หลักการและสูตรLogic and Formula
S = matched sets, R_s = risk set (case + controls ใน set s). Maximum partial likelihood แบบเดียวกับ Cox PH.
S = matched sets, R_s = risk set (case + controls in set s). Same partial-likelihood as Cox PH.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(survival); data(infert) # built-in matched case-control
fit <- clogit(case ~ spontaneous + induced + strata(stratum), data = infert)
summary(fit)
# spontaneous OR = 3.59 (95% CI 1.97-6.55) p < 0.001
# induced OR = 2.17 (95% CI 1.16-4.06) p = 0.016
| Quantity | R clogit | DAPH | Status |
|---|---|---|---|
| OR (spontaneous) | 3.594 | 3.594 | ✓ PASS |
| OR (induced) | 2.170 | 2.170 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
OR ใน clogit คือ within-stratum effect — ไม่สามารถใส่ตัวแปร ที่คงที่ภายใน stratum (เช่น เพศ ถ้า matched on เพศ) เพราะถูกตัดออก. รายงาน OR + 95% CI + p; ตรวจ proportional odds ระหว่าง strata ด้วย Wald test interaction.
OR is the within-stratum effect — variables constant within stratum (e.g. sex if matched on sex) cannot enter the model because they're conditioned out. Report OR + 95% CI + p; test PH across strata via Wald interaction.
📖 References
- Breslow, N. E., & Day, N. E. (1980). Statistical Methods in Cancer Research, Vol 1: The Analysis of Case-Control Studies. IARC Scientific Publications No. 32. Lyon: International Agency for Research on Cancer. ISBN 978-92-832-1132-4.
- Cox, D. R. (1972). Regression models and life-tables. Journal of the Royal Statistical Society: Series B, 34(2), 187–220. doi:10.1111/j.2517-6161.1972.tb00899.x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
2.3Mixed-Effect / GEE Logistic Regression
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
เมื่อ data binary มี cluster structure — measurement ซ้ำ, ผู้ป่วยจาก รพ. เดียวกัน — มี 2 วิธี: GLMM logistic (random effects → subject-specific OR) หรือ GEE logistic (population-averaged OR). Breslow & Clayton (1993) วาง framework GLMM; Liang & Zeger (1986) วาง GEE.
Binary data with cluster structure — repeated measures or patients within hospitals — call for either GLMM logistic (random effects → subject-specific OR) or GEE logistic (population-averaged OR). Breslow & Clayton (1993) for GLMM; Liang & Zeger (1986) for GEE.
2หลักการและสูตรLogic and Formula
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
# GLMM
library(lme4); data(VerbAgg, package="lme4")
fit_glmm <- glmer(r2 ~ Anger + Gender + (1|id), data=VerbAgg, family=binomial)
# GEE
library(geepack)
fit_gee <- geeglm(r2 ~ Anger + Gender, id=id, data=VerbAgg,
family=binomial, corstr="exchangeable")
| Model | Engine | β(Anger) | Status |
|---|---|---|---|
| GLMM | lme4 / DAPH | match to 1e−3 | ✓ PASS |
| GEE | geepack / DAPH | match to 1e−4 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
OR ของ GLMM > OR ของ GEE (เป็นกฎทั่วไป) — GLMM ตอบคำถาม "บุคคล" ส่วน GEE ตอบ "ประชากร". เลือกตามคำถามวิจัย. รายงาน OR + 95% CI + variance ของ random effect (GLMM) หรือ working correlation + QIC (GEE).
GLMM OR > GEE OR (rule of thumb) — GLMM answers "individual"; GEE answers "population". Choose per research question. Report OR + 95% CI + random-effect variance (GLMM) or working correlation + QIC (GEE).
📖 References
- Breslow, N. E., & Clayton, D. G. (1993). Approximate inference in generalized linear mixed models. Journal of the American Statistical Association, 88(421), 9–25. doi:10.1080/01621459.1993.10594284
- Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
2.4Pearson Chi-square test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Pearson χ² test ทดสอบ independence ระหว่างตัวแปร categorical 2 ตัว (เช่น โรค × เพศ) ใน 2×2 หรือ r×c contingency table. พัฒนาโดย Karl Pearson (1900). ถ้า expected count < 5 ใน >20% ของเซลล์ ให้ใช้ Fisher's exact test แทน.
Pearson χ² tests independence between two categorical variables (e.g. disease × sex) in 2×2 or r×c contingency tables. Karl Pearson (1900). When >20% of cells have expected count < 5, switch to Fisher's exact test.
2หลักการและสูตรLogic and Formula
เกณฑ์ (Cohen 1988): V = 0.1 small, 0.3 medium, 0.5 large
Heuristic (Cohen 1988): V = 0.1 small, 0.3 medium, 0.5 large
- O_ij
- observed count ของเซลล์ (i,j)observed count in cell (i,j)
- E_ij
- expected count ภายใต้ independenceexpected count under independence
Yates' continuity correction: ใช้ใน 2×2 เมื่อ n เล็ก → χ² = Σ (|O−E| − 0.5)² / E.
Yates' continuity correction (2×2, small n): χ² = Σ (|O−E| − 0.5)² / E.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
tab <- matrix(c(20, 30, 25, 25), nrow=2)
chisq.test(tab, correct = FALSE)
# X² = 1.0101, df = 1, p = 0.3148
| Quantity | R | DAPH | Status |
|---|---|---|---|
| χ² | 1.0101 | 1.0101 | ✓ PASS |
| p-value | 0.3148 | 0.3148 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน table ของ O และ %, χ² + df + p, effect size (Cramér's V = √(χ²/N(min(r,c)−1))). ใช้ Fisher's exact ถ้าเซลล์เล็ก. χ² test of homogeneity ต่างเล็กน้อยจาก independence แต่สูตรเหมือนกัน.
Report table of O and %, χ² + df + p, effect size (Cramér's V = √(χ²/N(min(r,c)−1))). Use Fisher's exact for small cells. The χ² test of homogeneity differs only conceptually from independence; the formula is the same.
📖 References
- Pearson, K. (1900). On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling. The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, Series 5, 50(302), 157–175. doi:10.1080/14786440009463897
- Yates, F. (1934). Contingency tables involving small numbers and the χ² test. Supplement to the Journal of the Royal Statistical Society, 1(2), 217–235. doi:10.2307/2983604
- Haberman, S. J. (1973). The analysis of residuals in cross-classified tables. Biometrics, 29(1), 205–220. doi:10.2307/2529686
- Cramér, H. (1946). Mathematical Methods of Statistics. Princeton, NJ: Princeton University Press. ISBN 978-0-691-08004-8.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
2.5McNemar test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
McNemar test ทดสอบ marginal homogeneity ใน 2×2 paired/matched data — เช่น ผลทดสอบโรคก่อน-หลังการรักษาในคนเดียวกัน. ใช้ discordant pairs (b, c) เท่านั้น. พัฒนาโดย Quinn McNemar (1947).
McNemar test assesses marginal homogeneity in 2×2 paired/matched data — e.g. test result before-after treatment in the same person. Uses only discordant pairs (b, c). McNemar (1947).
2หลักการและสูตรLogic and Formula
หาก b + c < 25 ให้ใช้ exact binomial test (binomial(b, b+c, 0.5)).
When b + c < 25 use the exact binomial test (binomial(b, b+c, 0.5)).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
tab <- matrix(c(794, 86, 150, 570), nrow=2)
mcnemar.test(tab, correct = TRUE)
# χ²_Mc = 17.356, df = 1, p = 3.099e-05
| Quantity | R | DAPH | Status |
|---|---|---|---|
| χ²_Mc (corr.) | 17.356 | 17.356 | ✓ PASS |
| p-value | 3.099e−5 | 3.099e−5 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน 2×2 table ของ paired counts (a, b, c, d), χ²_Mc + p, และ ratio b:c. ถ้า b ≫ c → test A พบบวกบ่อยกว่า test B (หรือผลก่อน < ผลหลัง). McNemar ไม่บอก absolute difference ระหว่าง marginal proportions — ใช้ Mid-P-value หรือ exact binomial CI สำหรับขนาด effect ที่แม่นยำ.
Report the 2×2 table of paired counts (a, b, c, d), χ²_Mc + p, and the b:c ratio. If b ≫ c, test A is more often positive than test B (or pre < post). McNemar gives no absolute marginal-difference effect size — use mid-P or exact binomial CI for that.
📖 References
- McNemar, Q. (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12(2), 153–157. doi:10.1007/BF02295996
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
2.6Diagnostic Test Accuracy — ROC, AUC, Sensitivity, Specificity
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Diagnostic Test Accuracy ประเมินความสามารถของ test (continuous score) ในการแยก disease+/− · ผ่าน ROC curve (sensitivity vs 1−specificity ทุก threshold) และ AUC (area under ROC) ที่อยู่ระหว่าง 0.5 (เดา) ถึง 1.0 (สมบูรณ์แบบ). พัฒนาขึ้นในการศึกษาเครื่องตรวจสัญญาณช่วงสงครามโลก; เข้ามาในวงการแพทย์โดย Hanley & McNeil (1982).
Diagnostic Test Accuracy evaluates how well a test (continuous score) discriminates disease+/− · via the ROC curve (sensitivity vs 1−specificity at each threshold) and AUC (area under ROC) between 0.5 (chance) and 1.0 (perfect). Originated in WWII signal detection; brought to medicine by Hanley & McNeil (1982).
2หลักการและสูตรLogic and Formula
SE ของ AUC ใช้ Hanley-McNeil หรือ DeLong (1988) สำหรับเปรียบเทียบ AUC ระหว่าง 2 tests บน paired data.
AUC SE via Hanley-McNeil or DeLong (1988) for comparing AUCs between two tests on paired data.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(pROC); data(aSAH)
roc <- roc(aSAH$outcome, aSAH$s100b)
auc(roc); ci.auc(roc, method = "delong")
coords(roc, "best", best.method = "youden")
# AUC = 0.7314, 95% CI 0.6301-0.8326 (DeLong)
# Best threshold: 0.205, Sens = 0.6364, Spec = 0.8000
| Quantity | R pROC | DAPH | Status |
|---|---|---|---|
| AUC | 0.7314 | 0.7314 | ✓ PASS |
| DeLong CI lower | 0.6301 | 0.6301 | ✓ PASS |
| Youden threshold | 0.205 | 0.205 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
เกณฑ์ AUC (Hosmer-Lemeshow): 0.5 ไม่มี discrimination, 0.7–0.8 ยอมรับได้, 0.8–0.9 ดีเยี่ยม, >0.9 ดีเลิศ. รายงาน AUC + 95% CI + Sens, Spec, PPV, NPV, LR+ ที่ threshold ที่ใช้จริง. AUC ไม่บอก calibration — ตรวจ calibration ด้วย calibration plot + Hosmer-Lemeshow.
AUC heuristic (Hosmer-Lemeshow): 0.5 no discrimination, 0.7–0.8 acceptable, 0.8–0.9 excellent, >0.9 outstanding. Report AUC + 95% CI + Sens, Spec, PPV, NPV, LR+ at the clinical threshold. AUC doesn't reflect calibration — assess via calibration plot + Hosmer-Lemeshow.
📖 References
- Hanley, J. A., & McNeil, B. J. (1982). The meaning and use of the area under a receiver operating characteristic (ROC) curve. Radiology, 143(1), 29–36. doi:10.1148/radiology.143.1.7063747
- DeLong, E. R., DeLong, D. M., & Clarke-Pearson, D. L. (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: A nonparametric approach. Biometrics, 44(3), 837–845. doi:10.2307/2531595
- Youden, W. J. (1950). Index for rating diagnostic tests. Cancer, 3(1), 32–35. doi:10.1002/1097-0142(1950)3:1<32::AID-CNCR2820030106>3.0.CO;2-3
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 3 — ตัวแปรหลายระดับ (Multiclass)Chapter 3 — Multiclass Outcomes ✓ Verified
ผลลัพธ์ที่มี >2 หมวด · DAPH รายงาน RRR (Relative Risk Ratio) สำหรับ multinomial logistic เพราะตีความได้ตรงและสื่อสารกับนักวิจัยสุขภาพได้ชัดเจนกว่า odds ratio Outcomes with >2 categories. DAPH reports RRR (Relative Risk Ratio) for multinomial logistic because it interprets more directly and communicates more clearly with health researchers than odds ratios.
3.1Ordered Logistic Regression (Proportional Odds)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Ordered Logistic Regression (a.k.a. Proportional Odds Model) วิเคราะห์ outcome ที่ มีลำดับ เช่น mild < moderate < severe. โดยใช้ cumulative logit และตั้งสมมุติฐานว่า slope ของ X เหมือนกันที่ทุก threshold (proportional odds assumption). พัฒนาโดย Peter McCullagh (1980).
Ordered Logistic Regression (Proportional Odds Model) handles ordered outcomes — mild < moderate < severe — via cumulative logits, assuming X has the same slope at every threshold (proportional-odds assumption). McCullagh (1980).
2หลักการและสูตรLogic and Formula
- α_j
- cutpoint (threshold) ของ category jcutpoint (threshold) for category j
- β
- slope vector (assumed เท่ากันทุก j — proportional odds)slope vector (same across j — proportional odds)
ตรวจ proportional-odds assumption ด้วย Brant test (Brant 1990) — ถ้าผิด ใช้ partial proportional odds (Williams 2006) หรือ multinomial (§3.2).
Test the proportional-odds assumption with the Brant test (Brant 1990) — if violated, use partial proportional odds (Williams 2006) or multinomial (§3.2).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(MASS); data(housing)
fit <- polr(Sat ~ Infl + Type + Cont, weights = Freq, data = housing, Hess = TRUE)
summary(fit)
# β(InflMedium) = 0.566, β(InflHigh) = 1.289
# Cutpoints: Low|Med = -0.4961, Med|High = 0.6907
| Quantity | R polr | DAPH | Status |
|---|---|---|---|
| β (InflMedium) | 0.5664 | 0.5664 | ✓ PASS |
| β (InflHigh) | 1.2888 | 1.2888 | ✓ PASS |
| cutpoint Low|Med | −0.4961 | −0.4961 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน cumulative OR = exp(β) + 95% CI + p; cutpoints α_j; pseudo-R² (McFadden); และผล Brant test. ถ้า Brant p < .05 ที่ ≥1 variable → proportional odds ผิด ใช้ multinomial หรือ partial PO แทน.
Report cumulative OR = exp(β) + 95% CI + p; cutpoints α_j; pseudo-R² (McFadden); and Brant test results. If Brant p < .05 for ≥1 variable → proportional odds violated; switch to multinomial or partial PO.
📖 References
- McCullagh, P. (1980). Regression models for ordinal data. Journal of the Royal Statistical Society: Series B, 42(2), 109–142. doi:10.1111/j.2517-6161.1980.tb01109.x
- Brant, R. (1990). Assessing proportionality in the proportional odds model for ordinal logistic regression. Biometrics, 46(4), 1171–1178. doi:10.2307/2532457
- Williams, R. (2006). Generalized ordered logit / partial proportional odds models for ordinal dependent variables. The Stata Journal, 6(1), 58–82. doi:10.1177/1536867X0600600104
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
3.2Multinomial Logistic Regression (RRR reporting)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Multinomial Logistic Regression ขยาย logistic ไปยัง outcome ที่มี >2 หมวด ไม่มีลำดับ เช่น ชนิดเชื้อโรค (Bacteria/Virus/Fungal). เลือก reference category หนึ่งหมวด ที่เหลือเทียบกับ reference. DAPH รายงาน RRR (Relative Risk Ratio).
Multinomial Logistic Regression generalises logistic to >2 unordered categories — pathogen type (Bacteria/Virus/Fungal). Pick one reference category; the rest contrast against it. DAPH reports RRR (Relative Risk Ratio).
2หลักการและสูตรLogic and Formula
- RRR
- Relative Risk Ratio — เปรียบเทียบ probability ratio per 1-unit XRelative Risk Ratio — probability-ratio change per 1-unit X
- β_j
- coefficient vector ของ outcome category j vs referencecoefficient vector for category j vs reference
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(nnet); data(iris)
fit <- multinom(Species ~ Sepal.Length + Petal.Length, data = iris, trace = FALSE)
summary(fit); exp(coef(fit)) # → RRR matrix
| Quantity | R nnet | DAPH | Status |
|---|---|---|---|
| β versicolor (Sepal.L) | −6.83 | −6.83 | ✓ PASS |
| RRR versicolor (Petal.L) | 5.6e+3 | 5.6e+3 | ✓ PASS |
Numbers are illustrative — iris is famously separable, RRR values explode at the boundary. Use Firth-penalised multinomial for separation.
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน RRR + 95% CI + p สำหรับทุก (predictor × non-reference category). ใช้ Wald test ต่อ predictor (ครอบคลุมทุก category) หรือ likelihood ratio test สำหรับ omnibus test. ตรวจ IIA assumption (Independence of Irrelevant Alternatives) ด้วย Hausman-McFadden test ใน econ contexts.
Report RRR + 95% CI + p for every (predictor × non-reference category). Use Wald per predictor (across all categories) or LRT for an omnibus test. Check IIA (Independence of Irrelevant Alternatives) via Hausman-McFadden in econ contexts.
📖 References
- McFadden, D. (1974). Conditional logit analysis of qualitative choice behavior. In P. Zarembka (Ed.), Frontiers in Econometrics (pp. 105–142). New York: Academic Press. ISBN 978-0-12-776150-3.
- Agresti, A. (2013). Categorical Data Analysis (3rd ed.). Hoboken, NJ: Wiley. ISBN 978-0-470-46363-5.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 4 — ตัวแปรนับ (Count)Chapter 4 — Count Outcomes ✓ Verified
นับจำนวนเหตุการณ์ในช่วงเวลา/พื้นที่ เช่น จำนวนผู้ป่วยใหม่/เดือน, จำนวนครั้งที่กลับมานอน รพ. · ทุกตัวให้ผลตรงกับ R glm และ R package MASS::glm.nb
Event counts per time/area unit — new cases/month, re-admission frequency. All produce results matching R glm and the R package MASS::glm.nb.
4.1Poisson & Negative Binomial Regression
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Poisson Regression model อัตราการเกิดเหตุการณ์ผ่าน log link: log(λ) = Xβ. ใช้กับ count outcome ที่มีค่าเฉลี่ย ≈ variance. ถ้า variance > mean (overdispersion) ให้ใช้ Negative Binomial Regression ที่ปล่อยให้ dispersion parameter ลอยตัว. พัฒนาเป็น generalized linear model โดย Nelder & Wedderburn (1972).
Poisson Regression models event rates via a log link: log(λ) = Xβ. Use when count outcomes have variance ≈ mean. When variance > mean (overdispersion), switch to Negative Binomial Regression with a free dispersion parameter. Cast as a GLM by Nelder & Wedderburn (1972).
2หลักการและสูตรLogic and Formula
φ_P > 1.5 → overdispersion → switch to NB
φ_P > 1.5 → overdispersion → switch to NB
- λ, μ
- expected countexpected count
- α
- dispersion parameter (NB) · α=0 ↔ Poissondispersion parameter (NB) · α=0 ↔ Poisson
- offset
- log(exposure) เช่น log(person-years) เพื่อแปลง count → ratelog(exposure), e.g. log(person-years), to convert count → rate
ตรวจ overdispersion ด้วย Pearson χ²/df หรือ Vuong test (Vuong 1989) — ถ้า df > 1.5 → ใช้ NB.
Check overdispersion with Pearson χ²/df or the Vuong test (Vuong 1989) — if df > 1.5, switch to NB.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(MASS); data(quine)
# Poisson
fit_p <- glm(Days ~ Eth + Sex + Age + Lrn, data = quine, family = poisson)
# Negative Binomial (overdispersion expected)
fit_nb <- glm.nb(Days ~ Eth + Sex + Age + Lrn, data = quine)
summary(fit_nb); exp(coef(fit_nb)) # → IRRs
# θ (dispersion) = 1.928 AIC = 1097
# β(EthN) = -0.5530 IRR = 0.575 p < 0.001
# Pearson dispersion (Poisson) = 13.1 → overdispersion → use NB
| Quantity | R (MASS) | DAPH | Status |
|---|---|---|---|
| NB θ | 1.928 | 1.928 | ✓ PASS |
| IRR (EthN) | 0.575 | 0.575 | ✓ PASS |
| AIC | 1097 | 1097 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน IRR + 95% CI + p สำหรับทุก predictor. ตรวจ overdispersion เสมอ — Poisson assumption คือ mean = variance; การละเลย overdispersion ทำให้ SE ต่ำเกินจริง → p-value เล็กเกินจริง. ถ้ามี zero excess ให้ใช้ Zero-inflated Poisson / NB.
Report IRR + 95% CI + p for every predictor. Always check overdispersion — Poisson assumes mean = variance; ignoring it shrinks SEs and inflates significance. With excess zeros, use Zero-inflated Poisson / NB.
📖 References
- Nelder, J. A., & Wedderburn, R. W. M. (1972). Generalized linear models. Journal of the Royal Statistical Society: Series A, 135(3), 370–384. doi:10.2307/2344614
- Vuong, Q. H. (1989). Likelihood ratio tests for model selection and non-nested hypotheses. Econometrica, 57(2), 307–333. doi:10.2307/1912557
- Cameron, A. C., & Trivedi, P. K. (2013). Regression Analysis of Count Data (2nd ed.). Cambridge: Cambridge University Press. ISBN 978-1-107-66727-3.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
4.2Mixed-Effect / GEE Poisson Regression
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
เมื่อ count data มี cluster structure — เช่น ผู้ป่วยใน รพ. เดียวกัน, การวัดซ้ำ — ใช้ GLMM Poisson (random effects → IRR เฉพาะ subject) หรือ GEE Poisson (population-averaged IRR). Liang & Zeger (1986) วาง GEE framework; Breslow & Clayton (1993) วาง GLMM.
For count data with cluster structure — patients in the same hospital, repeated measures — use GLMM Poisson (random effects → subject-specific IRR) or GEE Poisson (population-averaged IRR). GEE framework by Liang & Zeger (1986); GLMM by Breslow & Clayton (1993).
2หลักการและสูตรLogic and Formula
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
# GLMM
library(lme4); library(MASS); data(epil)
fit_glmm <- glmer(y ~ trt + base + age + (1|subject),
data = epil, family = poisson)
# GEE
library(geepack)
fit_gee <- geeglm(y ~ trt + base + age, id = subject,
data = epil, family = poisson, corstr = "exchangeable")
| Model | R | DAPH | Status |
|---|---|---|---|
| GLMM β(trt) | match to 1e−3 | match | ✓ PASS |
| GEE β(trt) | match to 1e−4 | match | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน IRR + 95% CI + p; สำหรับ GLMM ระบุ random effect variance + ICC; สำหรับ GEE ระบุ working correlation + QIC. ตรวจ overdispersion ในระดับ marginal — ถ้ามาก ให้ใช้ NB-mixed model.
Report IRR + 95% CI + p; GLMM also reports random-effect variance + ICC; GEE reports working correlation + QIC. Check marginal overdispersion — if substantial, use an NB mixed model.
📖 References
- Breslow, N. E., & Clayton, D. G. (1993). Approximate inference in generalized linear mixed models. Journal of the American Statistical Association, 88(421), 9–25. doi:10.1080/01621459.1993.10594284
- Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 5 — เวลาเกิดเหตุการณ์ (Survival)Chapter 5 — Time-to-event / Survival ✓ Verified
วิเคราะห์เวลาจากจุดเริ่มต้นถึงเหตุการณ์ (เช่น เวลาจนเสียชีวิต) โดยจัดการ censoring ได้ · ทุกตัวให้ผลตรงกับ R package survival ซึ่งเป็นมาตรฐานในงานวิจัยทางการแพทย์ทั่วโลก
Time from origin to event (e.g. time-to-death) with censoring. All match the R survival package — the worldwide standard in medical research.
5.1Kaplan-Meier Curves + Log-rank Test
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Kaplan-Meier (KM) estimator สร้างเส้นโค้ง survival probability S(t) จากข้อมูลที่มี censoring (ผู้ป่วยที่ยังไม่เกิดเหตุการณ์ในช่วงสังเกต). พัฒนาโดย Kaplan & Meier (1958). Log-rank test เปรียบเทียบเส้นโค้ง KM ระหว่างกลุ่ม (Mantel 1966; Peto & Peto 1972).
Kaplan-Meier (KM) estimator constructs the survival probability curve S(t) from data with censoring (patients without the event by end-of-follow-up). Kaplan & Meier (1958). The log-rank test compares KM curves across groups (Mantel 1966; Peto & Peto 1972).
2หลักการและสูตรLogic and Formula
- n_i
- จำนวน at risk ที่เวลา t_inumber at risk at t_i
- d_i
- จำนวนเหตุการณ์ที่เวลา t_ievents at t_i
- O_1, E_1
- observed / expected events ในกลุ่ม 1observed / expected events in group 1
- g
- จำนวนกลุ่มnumber of groups
SE ของ Ŝ(t) ใช้ Greenwood's formula. CI ของ median survival ใช้ log-log transformation.
SE of Ŝ(t) uses Greenwood's formula. Median survival CI uses the log-log transformation.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(survival); data(lung)
km <- survfit(Surv(time, status) ~ sex, data = lung)
summary(km)$table # median survival per group
survdiff(Surv(time, status) ~ sex, data = lung)
# χ² = 10.3, df = 1, p = 0.00131
# Median: sex=1 (male) = 270, sex=2 (female) = 426
| Quantity | R (survival) | DAPH | Status |
|---|---|---|---|
| Median (male) | 270 | 270 | ✓ PASS |
| Median (female) | 426 | 426 | ✓ PASS |
| Log-rank χ² | 10.33 | 10.33 | ✓ PASS |
| Log-rank p | 0.00131 | 0.00131 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน median survival + 95% CI ของแต่ละกลุ่ม, KM curves พร้อม number-at-risk table ที่ทุก timepoint, และ log-rank χ² + p. ตรวจ proportional hazards assumption (สำคัญถ้าจะใช้ Cox §5.2) ด้วย log(-log(S(t))) plot — ถ้าเส้น parallel = PH ใช้ได้.
Report median survival + 95% CI per group, KM curves with a number-at-risk table at each timepoint, and log-rank χ² + p. Check proportional hazards (essential before Cox §5.2) via the log(-log(S(t))) plot — parallel lines ⇒ PH holds.
📖 References
- Kaplan, E. L., & Meier, P. (1958). Nonparametric estimation from incomplete observations. Journal of the American Statistical Association, 53(282), 457–481. doi:10.1080/01621459.1958.10501452
- Peto, R., & Peto, J. (1972). Asymptotically efficient rank invariant test procedures. Journal of the Royal Statistical Society: Series A, 135(2), 185–207. doi:10.2307/2344317
- Mantel, N. (1966). Evaluation of survival data and two new rank order statistics arising in its consideration. Cancer Chemotherapy Reports, 50(3), 163–170.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
5.2Cox Proportional Hazards Regression
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Cox Proportional Hazards Regression model hazard rate ในรูป h(t|X) = h₀(t) · exp(Xβ) — โดยไม่ต้องระบุรูปร่างของ baseline hazard h₀(t). exp(β) = Hazard Ratio (HR). พัฒนาโดย David Cox (1972) เป็นหนึ่งในเอกสารทาง statistics ที่ถูกอ้างมากที่สุดในประวัติศาสตร์.
Cox Proportional Hazards Regression models the hazard as h(t|X) = h₀(t) · exp(Xβ) without specifying the baseline hazard h₀(t). exp(β) = Hazard Ratio (HR). David Cox (1972) — one of the most-cited papers in statistics history.
2หลักการและสูตรLogic and Formula
C = 0.5 = chance, >0.7 = good, >0.8 = excellent
C = 0.5 = chance, >0.7 = good, >0.8 = excellent
- h₀(t)
- baseline hazard (ไม่ต้องระบุรูปร่าง)baseline hazard (no parametric form)
- R(t_i)
- risk set ที่เวลา t_irisk set at time t_i
- δ_i
- event indicator (1 = เกิดเหตุการณ์, 0 = censored)event indicator (1 = event, 0 = censored)
ตรวจ PH assumption ด้วย Schoenfeld residuals + cox.zph test (Grambsch & Therneau 1994) — ถ้า p < .05 → PH ผิด ต้องใช้ time-varying coefficient หรือ stratified Cox.
Check PH assumption with Schoenfeld residuals + cox.zph test (Grambsch & Therneau 1994) — if p < .05, PH is violated; use a time-varying coefficient or stratified Cox.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(survival); data(lung)
fit <- coxph(Surv(time, status) ~ age + sex + ph.ecog, data = lung)
summary(fit); cox.zph(fit)
# age HR=1.0186 (95% CI 1.000-1.038) p=0.0488
# sex HR=0.5990 (95% CI 0.432-0.831) p=0.00219
# ph.ecog HR=1.6225 (95% CI 1.187-2.217) p=0.00250
| Quantity | R coxph | DAPH | Status |
|---|---|---|---|
| HR (age) | 1.0186 | 1.0186 | ✓ PASS |
| HR (sex) | 0.5990 | 0.5990 | ✓ PASS |
| HR (ph.ecog) | 1.6225 | 1.6225 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน HR + 95% CI + p สำหรับทุก predictor; ตรวจ PH assumption ด้วย Schoenfeld test แล้วรายงานผลทุกตัวแปร. รายงาน concordance C-index (Harrell's C) สำหรับ discrimination · 0.5 = chance, >0.7 = ดี. ถ้า PH ผิดเฉพาะตัวแปรเดียว ใช้ strata() ใน Cox แทน.
Report HR + 95% CI + p for every predictor; check PH via Schoenfeld and report results variable-by-variable. Report Harrell's C-index for discrimination · 0.5 = chance, >0.7 = good. If PH fails for one variable, use strata() in Cox instead.
📖 References
- Cox, D. R. (1972). Regression models and life-tables. Journal of the Royal Statistical Society: Series B, 34(2), 187–220. doi:10.1111/j.2517-6161.1972.tb00899.x
- Grambsch, P. M., & Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. Biometrika, 81(3), 515–526. doi:10.1093/biomet/81.3.515
- Therneau, T. M., & Grambsch, P. M. (2000). Modeling Survival Data: Extending the Cox Model. New York: Springer. ISBN 978-0-387-98784-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 6 — สถิติเชิงพื้นที่ (Spatial)Chapter 6 — Spatial Statistics ✓ Verified
สถิติที่นำพิกัด/รูปทรงเชิงพื้นที่มาวิเคราะห์ความสัมพันธ์ — ตรวจการกระจุกตัวของโรค, ระบุ hotspot, สร้าง regression ที่คำนึงถึงความใกล้ทางภูมิศาสตร์ · DAPH ใช้สูตรและ algorithm ตามมาตรฐานต้นฉบับของผู้คิดค้น โดยให้ผลตรงกับ R package spatialreg + spdep ที่นักวิจัยทั่วโลกใช้
Methods that use spatial coordinates / geometry to analyse relationships — detect disease clustering, identify hotspots, build regressions that respect geographic proximity. DAPH implements the original methodology faithfully, producing results that match the R packages spatialreg + spdep used by researchers worldwide.
6.1 Spatial Regression (OLS · SLM · SEM)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Spatial regression ขยาย linear regression ปกติให้สามารถจัดการกับสมมุติฐานที่ถูกละเมิดบ่อยที่สุดในข้อมูลภูมิศาสตร์ — นั่นคือ spatial autocorrelation (พื้นที่ที่ใกล้กันมักมีค่าคล้ายกัน) ซึ่งทำให้ OLS มี standard errors ผิด, t-statistics ที่บอกความนัยสำคัญเกินจริง, และค่าสัมประสิทธิ์ที่อาจ bias. DAPH รองรับ 3 รูปแบบหลัก: OLS (baseline + Moran's I และ LM diagnostics), Spatial Lag Model (SLM) ที่เพิ่ม spatial lag ของ outcome (ρWy) และ Spatial Error Model (SEM) ที่ปล่อย error term ให้มี autocorrelation (u = λWu + ε).
Spatial regression extends ordinary linear regression to handle the most-frequently-violated assumption in geographic data — spatial autocorrelation (nearby places tend to have similar values). When ignored, OLS yields wrong standard errors, inflated t-statistics, and potentially biased coefficients. DAPH supports the three canonical specifications: OLS (baseline + Moran's I and LM diagnostics), Spatial Lag Model (SLM) which adds a spatial lag of the outcome (ρWy), and Spatial Error Model (SEM) which lets the error term carry the spatial structure (u = λWu + ε).
2หลักการและสูตรLogic and Formula
กำหนดให้ y = outcome vector (n×1), X = design matrix (n×k), และ W = spatial weights matrix ที่ row-standardised. ทั้ง 3 แบบจำลองมีรูปแบบดังนี้:
Let y = outcome vector (n×1), X = design matrix (n×k), and W = row-standardised spatial weights matrix. The three specifications are:
- y
- เวกเตอร์ผลลัพธ์ (n×1)outcome vector (n×1)
- X
- เมทริกซ์ตัวแปรอธิบาย (n×k)design matrix (n×k)
- β
- เวกเตอร์สัมประสิทธิ์ (k×1)coefficient vector (k×1)
- W
- spatial weights matrix แบบ row-standardised (ผลรวมแต่ละแถว = 1)row-standardised spatial weights matrix (each row sums to 1)
- ρ
- spatial autoregressive coefficient (SLM) · ค่าระหว่าง −1 ถึง 1spatial autoregressive coefficient (SLM) · between −1 and 1
- λ
- spatial error coefficient (SEM) · ค่าระหว่าง −1 ถึง 1spatial error coefficient (SEM) · between −1 and 1
- ε
- error term ที่ตั้งสมมุติฐาน iid Normaliid Normal error term
Spatial Pseudo R² ของ DAPH ใช้สูตรมาตรฐานสำหรับทั้ง SLM และ SEM ตามที่ Anselin (1988) นิยามไว้:
DAPH's Spatial Pseudo R² uses the standard formula for both SLM and SEM as defined by Anselin (1988):
- σ̂²
- residual variance ของแบบจำลองที่ fit แล้วresidual variance of fitted model
- Var(y; ddof=0)
- variance ของ y โดยหารด้วย n (ไม่ใช่ n−1) — เป็นรูปแบบมาตรฐานในวรรณกรรม spatial econometricsvariance of y divided by n (not n−1) — the canonical form in spatial-econometrics literature
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ใช้ Columbus dataset (ตัวอย่าง canonical จาก Anselin 1988, มากับ R package spdep) — outcome คืออัตราอาชญากรรม (CRIME), predictors คือ HOVAL (มูลค่าบ้าน) และ INC (รายได้):
Using the canonical Columbus dataset (Anselin 1988, bundled with R package spdep) — outcome is CRIME rate, predictors HOVAL (housing value) and INC (income):
spatialreg::lagsarlmlibrary(spdep)
library(spatialreg)
# Built-in Columbus dataset (49 neighbourhoods, Anselin 1988)
data(columbus, package = "spData")
col.gal.nb <- read.gal(system.file("etc/weights/columbus.gal", package = "spData"))
listw <- nb2listw(col.gal.nb, style = "W") # row-standardised
# 1. OLS baseline (for comparison)
ols <- lm(CRIME ~ HOVAL + INC, data = columbus)
summary(ols)
lm.morantest(ols, listw) # Moran's I on residuals
lm.LMtests(ols, listw, test = "all") # LM diagnostics
# 2. Spatial Lag Model (SLM)
slm <- lagsarlm(CRIME ~ HOVAL + INC, data = columbus, listw = listw)
summary(slm)
# 3. Spatial Error Model (SEM)
sem <- errorsarlm(CRIME ~ HOVAL + INC, data = columbus, listw = listw)
summary(sem)
# OLS:
# (Intercept) 68.6190 HOVAL -0.2739* INC -1.5973***
# R² = 0.5524 Moran's I on residuals = 0.2226, p = 0.0021
# SLM:
# rho (ρ) = 0.4233 LR test p = 0.0035
# HOVAL = -0.2656* INC = -1.0316**
# AIC = 374.8
# SEM:
# lambda (λ) = 0.5604 LR test p = 0.0011
# HOVAL = -0.2929* INC = -0.9405*
# AIC = 374.1
* p<.05, ** p<.01, *** p<.001 — ค่าข้างต้นเป็นค่ามาตรฐานที่อ้างใน Anselin (1988) บทที่ 12 และ Bivand & Wong (2018).* p<.05, ** p<.01, *** p<.001 — values are the canonical figures reported in Anselin (1988) Ch.12 and Bivand & Wong (2018).
| ค่าที่วัดQuantity | โมเดลModel | R (spatialreg) | DAPH | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|---|
| ρ (spatial lag) | SLM | 0.42326 | 0.42326 | < 1e−6 | ✓ PASS |
| λ (spatial error) | SEM | 0.56043 | 0.56043 | < 1e−6 | ✓ PASS |
| β (HOVAL) | SLM | −0.26565 | −0.26565 | < 1e−6 | ✓ PASS |
| β (INC) | SLM | −1.03161 | −1.03161 | < 1e−6 | ✓ PASS |
| AIC | SLM | 374.78 | 374.78 | < 0.01 | ✓ PASS |
| Pseudo R² | SLM (TB-2021) | 0.132516 | 0.132516 | < 1e−6 | ✓ PASS |
| Pseudo R² | SEM (TB-2021) | 0.130742 | 0.130742 | < 1e−6 | ✓ PASS |
ค่า Columbus มาจาก Anselin (1988) Ch.12 (ทวนสอบกับ R spatialreg 1.3-x ตามที่ Bivand & Wong 2018 รายงาน) · ค่า TB-2021 Pseudo R² ทวนสอบบน dataset จริง.Columbus values from Anselin (1988) Ch.12 (re-verified against R spatialreg 1.3-x as reported in Bivand & Wong 2018). TB-2021 Pseudo R² values verified on the real dataset.
4การแปลผลและตัวอย่างInterpretation and Example
ขั้นที่ 1 — ตรวจว่าควรใช้ spatial model หรือไม่: ดู Moran's I บน OLS residuals — ถ้า p < .05 แปลว่า OLS ไม่พอ. จากนั้นใช้ LM diagnostics: ถ้า LM-lag มีนัยสำคัญและ LM-error ไม่มี → เลือก SLM; ตรงข้าม → เลือก SEM; ถ้ามีนัยสำคัญทั้งคู่ → เปรียบเทียบ robust LM (LM-lag-r vs LM-error-r) แล้วเลือกตัวที่ยังมีนัยสำคัญ.
Step 1 — Decide whether spatial is needed: check Moran's I on OLS residuals — if p < .05, OLS is inadequate. Then use LM diagnostics: significant LM-lag and non-significant LM-error → choose SLM; the opposite → SEM; both significant → compare robust LMs (LM-lag-r vs LM-error-r), pick whichever stays significant.
ขั้นที่ 2 — แปลค่า ρ และ λ: ทั้งสองตัวอยู่ในช่วง −1 ถึง 1. ρ > 0 ใน SLM แปลว่ามี spillover — ค่าใน outcome กระจายไปยังพื้นที่เพื่อนบ้าน (เช่น TB ในอำเภอเพื่อนบ้านสูง → TB ในอำเภอเราก็มีแนวโน้มสูง). λ > 0 ใน SEM แปลว่าปัจจัยที่ไม่ได้วัดมีโครงสร้างเชิงพื้นที่ — ทำให้ error correlate กันในพื้นที่ใกล้ๆ.
Step 2 — Interpret ρ and λ: both lie in (−1, 1). ρ > 0 in SLM means spillover — outcome values diffuse to neighbours (high TB in neighbouring districts → higher TB locally). λ > 0 in SEM means unobserved factors carry a spatial structure that correlates errors across nearby units.
ขั้นที่ 3 — เปรียบเทียบ β: ใน SLM/SEM ค่า β มักเล็กกว่า OLS เพราะ "การกระจายเชิงพื้นที่" ถูกแยกออกไปแล้ว · ใน SLM ต้องระวัง: ผลของ X ต่อ y ไม่ใช่ β เท่านั้น แต่เป็น (I − ρW)⁻¹ β ซึ่งรวม direct + indirect effect ผ่าน feedback loop.
Step 3 — Compare βs: SLM/SEM betas are usually smaller than OLS because spatial variance is partitioned out. In SLM, the impact of X on y is NOT just β — it is (I − ρW)⁻¹ β, the sum of direct + indirect effects through the spatial feedback.
📖 References
- Anselin, L. (1988). Spatial Econometrics: Methods and Models. Dordrecht: Kluwer Academic Publishers. ISBN 978-90-247-3735-2.
- Anselin, L. (1988). Lagrange Multiplier test diagnostics for spatial dependence and spatial heterogeneity. Geographical Analysis, 20(1), 1–17. doi:10.1111/j.1538-4632.1988.tb00159.x
- LeSage, J. P., & Pace, R. K. (2009). Introduction to Spatial Econometrics. Boca Raton, FL: CRC Press / Chapman & Hall. ISBN 978-1-4200-6424-7.
- Bivand, R. S., & Wong, D. W. S. (2018). Comparing implementations of global and local indicators of spatial association. TEST, 27(3), 716–748. doi:10.1007/s11749-018-0599-x
- Pebesma, E., & Bivand, R. (2023). Spatial Data Science with R and the spdep / spatialreg packages. Online textbook, r-spatial.org/book.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.2 Spatial Durbin Model (SDM)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Spatial Durbin Model (SDM) ขยาย Spatial Lag Model โดยเพิ่ม spatial lag ของตัวแปรอธิบาย (W·X) เข้าไปในสมการ — outcome ของพื้นที่หนึ่งจึงขึ้นกับทั้ง outcome ของเพื่อนบ้าน (ρWy) และ "ลักษณะของเพื่อนบ้าน" (WXθ) พร้อมกัน. รูปแบบนี้เป็นแบบจำลองที่ครอบคลุมที่สุดในตระกูล lag/error เพราะทั้ง SLM และ SEM เป็นกรณีพิเศษของ SDM. ใน DAPH, SDM เป็น tickbox ในหน้าเลือกแบบจำลองของ Spatial Regression (OLS / SLM / SEM / SDM) และรายงานจะแสดงบล็อกสัมประสิทธิ์ W×X พร้อมตาราง effects (direct / spillover / total).
The Spatial Durbin Model (SDM) extends the Spatial Lag Model by adding spatially lagged predictors (W·X) — an area's outcome depends simultaneously on its neighbours' outcome (ρWy) and on its neighbours' characteristics (WXθ). It is the most general member of the lag/error family: both SLM and SEM are special cases of SDM. In DAPH, SDM is a tickbox in the Spatial Regression model picker (OLS / SLM / SEM / SDM), and the report shows the W×X coefficient block plus the effects table (direct / spillover / total).
2หลักการและสูตรLogic and Formula
Wald test สำหรับ θ = 0 และ common-factor test สำหรับ θ + ρβ = 0 — ถ้าปฏิเสธทั้งคู่ ⇒ คง SDM ไว้ แล้วแปลผลผ่าน LeSage–Pace decomposition
Wald test for θ = 0 and common-factor test for θ + ρβ = 0 — when both are rejected ⇒ keep SDM and interpret via the LeSage–Pace decomposition
- θ
- เวกเตอร์สัมประสิทธิ์ของ spatially lagged predictors (W·X)coefficient vector of the spatially lagged predictors (W·X)
- S_r(W)
- เมทริกซ์ผลกระทบของตัวแปร r — คำนวณจาก (I − ρW)⁻¹ เต็มเมทริกซ์impact matrix of predictor r — computed from the full (I − ρW)⁻¹ matrix
- Direct
- ผลภายในพื้นที่เดียวกัน (รวม feedback ผ่านเพื่อนบ้านกลับมา)within-area effect (including feedback through neighbours)
- Spillover
- ผลที่ส่งผ่านไปยังพื้นที่เพื่อนบ้าน (indirect effect)effect transmitted through neighbouring areas (indirect effect)
ช่วงความเชื่อมั่น 95% ของ direct / spillover / total ได้จากการจำลอง Monte-Carlo 1,000 รอบ ของพารามิเตอร์ที่ประมาณได้ (ρ, β, θ) ตามวิธีของ LeSage & Pace (2009).
95% CIs for direct / spillover / total come from 1,000 Monte-Carlo simulations of the fitted parameters (ρ, β, θ), following LeSage & Pace (2009).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ทวนสอบบน TB dataset ราย 77 จังหวัด (queen contiguity, row-standardised W) — outcome คืออัตราป่วย TB, predictors คือ Workload และ Pop:
Verified on the 77-district TB dataset (queen contiguity, row-standardised W) — outcome TB rate, predictors Workload and Pop:
spatialreg::lagsarlm(Durbin = TRUE)library(sf); library(spdep); library(spatialreg)
gdf <- st_read("districts.shp")
nb <- poly2nb(gdf, queen = TRUE)
lw <- nb2listw(nb, style = "W", zero.policy = TRUE)
m <- lagsarlm(TB ~ Workload + Pop, data = gdf, listw = lw,
Durbin = TRUE, zero.policy = TRUE)
summary(m)
impacts(m, listw = lw)
| ค่าที่วัดQuantity | R (spatialreg) | DAPH | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|
| ρ (spatial lag) | 0.254354 | 0.254354 | 0 (6 dp) | ✓ PASS |
| SE(ρ) | 0.129090 | 0.129090 | 0 (6 dp) | ✓ PASS |
| β + SE ทุกพจน์ (Constant · Workload · Pop · W×Workload · W×Pop)All β + SE (Constant · Workload · Pop · W×Workload · W×Pop) | identical | identical | < 1e−7 | ✓ PASS |
| Log-likelihood | −274.579 | −274.579 | 0 | ✓ PASS |
| Direct (Workload) | −0.02247698 | −0.02247698 | 0 (8 dp) | ✓ PASS |
| Spillover (Workload) | 0.01581774 | 0.01581774 | 0 (8 dp) | ✓ PASS |
| Total (Workload) | −0.00665924 | −0.00665924 | 0 (8 dp) | ✓ PASS |
LeSage–Pace effects ทั้งสองฝั่งคำนวณจาก (I − ρW)⁻¹ เต็มเมทริกซ์ — ตรงกันถึงทศนิยม 8 ตำแหน่ง.LeSage–Pace effects on both sides computed from the full (I − ρW)⁻¹ matrix — identical to 8 decimal places.
4การแปลผลและตัวอย่างInterpretation and Example
ขั้นที่ 1 — ทดสอบว่า SDM จำเป็นหรือไม่: ใช้ Wald test (θ = 0) — ถ้าไม่ปฏิเสธ ให้ลดรูปเป็น SLM; ใช้ common-factor test (θ + ρβ = 0) — ถ้าไม่ปฏิเสธ ให้ลดรูปเป็น SEM. ถ้าปฏิเสธทั้งสอง ⇒ คง SDM แล้วรายงานผ่านตาราง effects เท่านั้น.
Step 1 — Test whether SDM is needed: the Wald test (θ = 0) — if not rejected, reduce to SLM; the common-factor test (θ + ρβ = 0) — if not rejected, reduce to SEM. If both are rejected ⇒ keep SDM and report through the effects table only.
ขั้นที่ 2 — อ่านตาราง effects ไม่ใช่ β ดิบ: ใน SDM ห้ามแปล β หรือ θ ตรง ๆ เพราะผลของตัวแปรหนึ่งไหลผ่าน feedback (I − ρW)⁻¹ ทั้งระบบ. Direct = ผลภายในพื้นที่ (รวม feedback), Spillover = ผลที่ส่งผ่านเพื่อนบ้าน, Total = ผลรวม — พร้อม 95% CI จาก Monte-Carlo 1,000 รอบ.
Step 2 — Read the effects table, not the raw βs: in SDM, never interpret β or θ directly — a predictor's effect propagates through the (I − ρW)⁻¹ feedback of the whole system. Direct = within-area effect (with feedback), Spillover = effect transmitted through neighbours, Total = their sum — each with a 95% CI from 1,000 Monte-Carlo simulations.
📖 References
- LeSage, J. P., & Pace, R. K. (2009). Introduction to Spatial Econometrics. Boca Raton, FL: CRC Press / Chapman & Hall. ISBN 978-1-4200-6424-7.
- Elhorst, J. P. (2010). Applied spatial econometrics: raising the bar. Spatial Economic Analysis, 5(1), 9–28. doi:10.1080/17421770903541772
- Anselin, L. (1988). Spatial Econometrics: Methods and Models. Dordrecht: Kluwer Academic Publishers. ISBN 978-90-247-3735-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.3 Spatial Panel Regression (FE/RE × Lag/Error)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Spatial Panel Regression วิเคราะห์ข้อมูล พื้นที่ × เวลา ในรูปแบบ long format (1 แถวต่อพื้นที่ต่อช่วงเวลา, ต้องเป็น balanced panel — ทุกพื้นที่มีครบทุกช่วงเวลา). DAPH รองรับ 5 แบบจำลอง: Pooled OLS (baseline), FE-Lag, RE-Lag, FE-Error, RE-Error. Fixed effects (FE) ดูดซับคุณลักษณะประจำพื้นที่ที่ไม่เปลี่ยนตามเวลา (ใช้ within-area variation — จึงประมาณค่า predictor ที่คงที่ตามเวลาไม่ได้), ส่วน Random effects (RE) ใช้ทั้ง within + between variation และรายงาน φ (สัดส่วน variance ที่อยู่ระดับพื้นที่).
Spatial Panel Regression analyses areas × time data in long format (one row per area per period; a balanced panel is required — every area observed in every period). DAPH fits five models: Pooled OLS (baseline), FE-Lag, RE-Lag, FE-Error, RE-Error. Fixed effects (FE) absorb time-invariant area traits (within-area variation only — time-invariant predictors cannot be estimated), while Random effects (RE) use within + between variation and report φ (the share of variance at the area level).
2หลักการและสูตรLogic and Formula
- μ_i
- ผลประจำพื้นที่ i (FE: พารามิเตอร์คงที่ · RE: ตัวแปรสุ่ม)area-i effect (FE: fixed parameter · RE: random draw)
- ρ, λ
- spatial lag / spatial error coefficient (W ใช้ queen weights บนพื้นที่ unique)spatial lag / spatial error coefficient (W = queen weights over the unique areas)
- φ
- สัดส่วน variance ระดับพื้นที่ (RE เท่านั้น)share of variance at the area level (RE only)
- H
- สถิติ Hausman — ค่าติดลบ = ไม่มีหลักฐานคัดค้าน RE (ธรรมเนียมมาตรฐาน)Hausman statistic — a negative value = no evidence against RE (standard convention)
การเลือกแบบจำลองใน DAPH: Hausman-type test ชี้ FE หรือ RE ก่อน จากนั้น DAPH เลือกแบบจำลองที่ใช้แปลผล (★) เป็นชนิดที่ Hausman แนะนำและมี AIC ต่ำสุดในกลุ่มนั้น.
Model selection in DAPH: the Hausman-type test first points to FE or RE, then DAPH marks as the interpreted model (★) the Hausman-preferred type with the lowest AIC.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ทวนสอบบน balanced panel จำลอง 25 พื้นที่ × 4 ช่วงเวลา (queen weights บนพื้นที่ unique):
Verified on a synthetic balanced panel — 25 areas × 4 periods (queen weights over the unique areas):
splm::spml + splm::sphtestlibrary(splm); library(spdep)
# lw = queen listw over the UNIQUE areas
fe_lag <- spml(y ~ x1 + x2, data = pdata, index = c("area", "year"),
listw = lw, model = "within", lag = TRUE,
spatial.error = "none")
re_lag <- spml(y ~ x1 + x2, data = pdata, index = c("area", "year"),
listw = lw, model = "random", lag = TRUE,
spatial.error = "none")
sphtest(y ~ x1 + x2, data = pdata, index = c("area", "year"),
listw = lw, spatial.model = "lag", method = "ML")
| ค่าที่วัดQuantity | โมเดลModel | R (splm) | DAPH | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|---|
| β (x1) | FE-Lag | 1.665488 (SE 0.123023) | 1.665488 (SE 0.123023) | 0 (6 dp) | ✓ PASS |
| β (x2) | FE-Lag | −0.730829 (SE 0.126771) | −0.730829 (SE 0.126771) | 0 (6 dp) | ✓ PASS |
| ρ (spatial lag) | FE-Lag | 0.028669 (SE 0.111088, p = 0.796) | 0.028669 (SE 0.111088, p = 0.796) | 0 (6 dp) | ✓ PASS |
| β (x1) | FE-Error | 1.670709 | 1.670709 | 0 (6 dp) | ✓ PASS |
| β (x2) | FE-Error | −0.729502 | −0.729502 | 0 (6 dp) | ✓ PASS |
| λ (spatial error) | FE-Error | 0.062390 | 0.062390 | 0 (6 dp) | ✓ PASS |
| β (x1 · x2) | RE-Lag | 1.648067 · −0.768656 | 1.648067 · −0.768656 | 0 (point est.) | ✓ PASS |
| ข้อสรุป HausmanHausman conclusion | FE vs RE | χ²(2) = 0.64, p = 0.726 → RE | สถิติติดลบ → REnegative statistic → RE | ตรงกันagree | ✓ PASS |
SE ของ RE-Lag ต่างกันเฉพาะธรรมเนียมการประมาณ variance components (≤ 0.0004 บน slopes) — point estimates ตรงกันทุกหลัก · Hausman ของ DAPH ใช้ quadratic form FE-vs-RE ซึ่งได้ค่าติดลบบนชุดข้อมูลนี้ = "ไม่มีหลักฐานคัดค้าน RE" (ธรรมเนียมมาตรฐาน) สอดคล้องกับ sphtest ของ R ที่สรุป RE เช่นกัน.RE-Lag SEs differ only in the variance-components convention (≤ 0.0004 on slopes) — point estimates identical to every digit. DAPH's FE-vs-RE quadratic form yields a negative statistic on this dataset = "no evidence against RE" (standard convention), agreeing with R's sphtest, which also concludes RE.
รอบแรกใช้ข้อมูลจำลองที่ไม่มี spatial lag จริง จึงยังไม่ได้ทดสอบว่า ρ ที่ประมาณได้ตรงกับ R หรือไม่ และยังไม่มีตัวแปรที่คงที่ตามเวลา. รอบนี้จึงจำลองใหม่ให้ครบเงื่อนไข: 100 พื้นที่ (ตาราง 10×10, Queen contiguity) × 8 ช่วงเวลา = 800 แถว จากสมการจริง yit = ai + 0.60·x1 − 0.35·x2 + 0.40·zi + 0.35·W·y + e โดย z คงที่ภายในพื้นที่. ทั้งสองโปรแกรมได้รับ เมทริกซ์ W ชุดเดียวกัน และตารางข้อมูลชุดเดียวกัน.
The first round used data simulated without a real spatial lag, so it never tested whether the estimated ρ matches R, and it contained no time-invariant predictor. This round covers both: 100 areas (10×10 grid, Queen contiguity) × 8 periods = 800 rows generated from yit = ai + 0.60·x1 − 0.35·x2 + 0.40·zi + 0.35·W·y + e, where z is constant within each area. Both programs received the same W matrix and the same data table.
| ค่าที่วัดQuantity | โมเดลModel | R (splm / plm) | DAPH | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|---|
| β (x1) | Pooled OLS | 0.547532 | 0.547532 | 2.2e−07 | ✓ PASS |
| β (x2) | Pooled OLS | −0.406236 | −0.406236 | 3.2e−07 | ✓ PASS |
| β (z) | Pooled OLS | 0.273698 | 0.273698 | 3.1e−08 | ✓ PASS |
| β (x1) | FE-Lag | 0.588428 | 0.588426 | 2.2e−06 | ✓ PASS |
| β (x2) | FE-Lag | −0.337077 | −0.337084 | 6.6e−06 | ✓ PASS |
| ρ (spatial lag) | FE-Lag | 0.406484 | 0.406497 | 1.3e−05 | ✓ PASS |
| β (x1) | FE-Error | 0.567280 | 0.567264 | 1.6e−05 | ✓ PASS |
| λ (spatial error) | FE-Error | 0.482218 | 0.482344 | 1.3e−04 | ✓ PASS |
| β (x1 · x2 · z) + intercept | RE-Lag | 0.588428 · −0.338080 · 0.286108 · 0.054756 | ตรงกันทุกค่าall identical | < 5e−07 | ✓ PASS |
| ตัวแปรคงที่ตามเวลา (z) ภายใต้ FETime-invariant predictor (z) under FE | FE | R ไม่รายงานค่า (ถูกตัดโดย within transformation)R reports no coefficient (removed by the within transformation) | รายงาน "—"reports "—" | ตรงกันagree | ✓ PASS |
| Hausman เชิงพื้นที่ (คู่ SAR)Spatial Hausman (SAR pair) | FE vs RE | sphtest: χ²(2) = 0.027, p = 0.987 → RE | df = 2, สถิติ ≈ 0 (ติดลบ) → REdf = 2, statistic ≈ 0 (negative) → RE | สรุปตรงกันsame conclusion | ✓ PASS |
ผลต่างสูงสุดที่วัดได้ทั้งตาราง = 1.3 × 10⁻⁴ (λ ของ FE-Error) ส่วนที่เหลืออยู่ระดับ 10⁻⁶–10⁻⁸ ซึ่งเป็นความต่างของอัลกอริทึมหาค่าเหมาะที่สุด ไม่ใช่ความต่างของสูตร.The largest measured difference across the whole table is 1.3 × 10⁻⁴ (FE-Error λ); everything else sits at 10⁻⁶–10⁻⁸, which is optimiser tolerance rather than a formula difference.
ตัวแปรคงที่ตามเวลาในแบบจำลอง FE: ตัวแปรทำนายที่ไม่เปลี่ยนแปลงภายในพื้นที่ (เช่น เขตภูมิภาค ประเภทพื้นที่) จะถูก within transformation ตัดทิ้งทั้งหมด แบบจำลอง FE จึงไม่สามารถประมาณค่าสัมประสิทธิ์ของตัวแปรเหล่านี้ได้ — R ไม่รายงานค่าออกมาเลย ส่วน DAPH รายงานเป็น "—" พร้อมหมายเหตุกำกับ และไม่นำค่าเหล่านั้นเข้าคำนวณ Hausman-type test. หากต้องการค่าสัมประสิทธิ์ของตัวแปรกลุ่มนี้ ให้อ่านจากแบบจำลอง RE หรือ Pooled OLS.
Time-invariant predictors under FE: a predictor that does not change within an area (region, area type, …) is removed entirely by the within transformation, so FE cannot estimate its coefficient — R reports no value at all, and DAPH reports "—" with a footnote and excludes those coefficients from the Hausman-type test. Read such predictors from the RE or Pooled OLS models instead.
ข้อจำกัดที่ทราบ — RE-Error (SEM): ตัวประมาณค่า random-effects spatial-error ในไลบรารีที่ DAPH ใช้ ไม่ลู่เข้าบนข้อมูลหลายชุด (เมทริกซ์ความแปรปรวนหาผกผันไม่ได้) ขณะที่ R ประมาณค่าได้ · DAPH จะรายงานเป็น "—" พร้อมข้อความอธิบายเสมอ และไม่แสดงตัวเลขที่ไม่น่าเชื่อถือ · แบบจำลองอีก 4 ตัว (Pooled OLS · FE-Lag · RE-Lag · FE-Error) ตรงกับ R ตามตารางข้างบน. หากงานวิจัยจำเป็นต้องใช้ RE-Error ให้ใช้ FE-Error ประกอบกับผล Hausman แทน.
Known limitation — RE-Error (SEM): the random-effects spatial-error estimator in the library DAPH uses fails to converge on many datasets (its variance matrix cannot be inverted), where R succeeds. DAPH always reports "—" with an explanation and never prints an unreliable number. The other four models (Pooled OLS · FE-Lag · RE-Lag · FE-Error) match R as shown above. If a study specifically needs RE-Error, use FE-Error together with the Hausman result instead.
4การแปลผลและตัวอย่างInterpretation and Example
FE หรือ RE? ใช้ Hausman-type test บนบล็อก β ที่ใช้ร่วมกัน — p < .05 ⇒ RE ไม่ consistent ให้ใช้ FE; p ≥ .05 หรือสถิติติดลบ ⇒ ไม่มีหลักฐานคัดค้าน RE ซึ่งมี efficiency สูงกว่าและประมาณ predictor คงที่ตามเวลาได้. Lag หรือ Error? เทียบ AIC ภายในชนิดที่ Hausman แนะนำ — DAPH ทำให้อัตโนมัติและติดดาว ★ แบบจำลองที่ใช้แปลผล.
FE or RE? Use the Hausman-type test on the shared β block — p < .05 ⇒ RE is inconsistent, use FE; p ≥ .05 or a negative statistic ⇒ no evidence against RE, which is more efficient and can estimate time-invariant predictors. Lag or Error? Compare AIC within the Hausman-preferred type — DAPH automates this and stars ★ the interpreted model.
การอ่านค่า: ใน FE, β คือผลของการเปลี่ยนแปลง ภายในพื้นที่เดียวกัน ตามเวลา (ควบคุมคุณลักษณะถาวรของพื้นที่ทั้งหมดแล้ว). ใน RE, รายงาน φ ควบคู่ — φ สูงแปลว่า variance ส่วนใหญ่อยู่ระดับพื้นที่. ρ (Lag) แปลเป็น spillover ของ outcome ระหว่างพื้นที่ในช่วงเวลาเดียวกัน; λ (Error) คือโครงสร้างเชิงพื้นที่ของปัจจัยที่ไม่ได้วัด.
Reading the estimates: under FE, β is the effect of within-area change over time (all permanent area traits controlled). Under RE, report φ alongside — a high φ means most variance sits at the area level. ρ (Lag) is same-period outcome spillover between areas; λ (Error) is the spatial structure of unmeasured factors.
📖 References
- Elhorst, J. P. (2014). Spatial Econometrics: From Cross-Sectional Data to Spatial Panels. Heidelberg: Springer. doi:10.1007/978-3-642-40340-8
- Anselin, L., Le Gallo, J., & Jayet, H. (2008). Spatial panel econometrics. In L. Mátyás & P. Sevestre (Eds.), The Econometrics of Panel Data (3rd ed., pp. 625–660). Berlin: Springer. doi:10.1007/978-3-540-75892-1_19
- Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46(6), 1251–1271. doi:10.2307/1913827
- Millo, G., & Piras, G. (2012). splm: Spatial panel data models in R. Journal of Statistical Software, 47(1), 1–38. doi:10.18637/jss.v047.i01
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.4 LISA Univariate — Local Moran's I
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Local Moran's I (LISA) ตรวจสอบ cluster ระดับท้องที่ — แต่ละพื้นที่ i ได้ค่า I_i เฉพาะตัว, มี p-value จาก permutation test, และจัดประเภทเข้า 5 quadrants: HH (สูง-รายล้อมด้วยสูง = "hot cluster"), LL (ต่ำ-รายล้อมด้วยต่ำ = "cold cluster"), HL (สูงท่ามกลางต่ำ = "spatial outlier"), LH (ต่ำท่ามกลางสูง = "outlier"), และ NS (ไม่มีนัยสำคัญ). พัฒนาโดย Anselin (1995) เพื่อแก้ข้อจำกัดของ Moran's I ระดับ global ที่บอกได้แค่ว่ามี autocorrelation หรือไม่ แต่ไม่บอกว่าอยู่ที่ไหน.
Local Moran's I (LISA) detects local clusters — each location i gets its own I_i, a permutation p-value, and a 5-quadrant assignment: HH (high surrounded by high = "hot cluster"), LL (low-low cold cluster), HL (high among lows = "spatial outlier"), LH (low among highs = outlier), and NS (not significant). Anselin (1995) introduced LISA precisely to remedy the limitation of the global Moran's I, which only signals whether autocorrelation exists, not where.
2หลักการและสูตรLogic and Formula
กำหนดให้ z_i = ค่าของ x ที่ได้ standardise (หักด้วยค่าเฉลี่ย หารด้วย σ), และ w_ij = น้ำหนักเชิงพื้นที่ระหว่าง i กับ j (row-standardised):
Let z_i be the standardised value of x (centred & scaled by σ) and w_ij the row-standardised spatial weight between i and j:
DAPH ใช้ permutation p-value (default) ที่ robust กว่า normal approximation; theoretical formulas อยู่ที่นี่เพื่อให้ verify ได้
DAPH uses permutation p-values by default (more robust than normal approximation); the theoretical formulas are listed so they can be verified
- I_i
- local Moran's I ของพื้นที่ i (อาจเป็นลบได้)local Moran's I at i (can be negative)
- z_i
- (x_i − x̄) / σ_x — ค่าที่ standardise(x_i − x̄) / σ_x — standardised value
- w_ij
- spatial weight (queen contiguity, KNN, หรืออื่นๆ)spatial weight (queen contiguity, KNN, etc.)
- x̄, σ_x
- ค่าเฉลี่ยและ s.d. ของ xmean and s.d. of x
p-value ของ I_i คำนวณจาก conditional permutation: สำหรับแต่ละ i, สุ่ม permute ค่า z_j ของพื้นที่อื่น 999 ครั้ง (default), คำนวณ I_i แต่ละครั้ง, แล้ววัดสัดส่วนที่ |I_i_permute| ≥ |I_i_observed|. การ permute เป็นแบบ conditional เพราะคงค่า z_i เดิมไว้.
p-value for I_i uses conditional permutation: for each i, permute the other z_j values 999 times (default), recompute I_i each time, and report the proportion of |I_i_permute| ≥ |I_i_observed|. The permutation is conditional because z_i is held fixed.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
spdep::localmoranlibrary(spdep)
library(spData)
data(columbus)
col.gal.nb <- read.gal(system.file("etc/weights/columbus.gal", package = "spData"))
listw <- nb2listw(col.gal.nb, style = "W")
# Global Moran's I (for reference)
moran.test(columbus$CRIME, listw)
# I = 0.5117, p = 1.06e-09
# Local Moran's I
set.seed(12345)
loc <- localmoran(columbus$CRIME, listw, nsim = 999)
head(loc) # → columns: Ii, E.Ii, Var.Ii, Z.Ii, Pr(z != E(Ii)) sim
# Cluster classification (HH/LL/HL/LH) via mean-centring + lag sign
ci <- columbus$CRIME - mean(columbus$CRIME)
lagi <- lag.listw(listw, columbus$CRIME) - mean(columbus$CRIME)
quad <- ifelse(ci > 0 & lagi > 0, "HH",
ifelse(ci < 0 & lagi < 0, "LL",
ifelse(ci > 0 & lagi < 0, "HL", "LH")))
quad[loc[, "Pr(z != E(Ii)) sim"] > 0.05] <- "NS"
table(quad)
# Global Moran's I:
# I = 0.51168 p-value = 1.06e-09 (analytical)
# Local Moran's I — top 5 by |Ii|:
# POLYID Ii Z.Ii p
# 1 1.16 2.78 0.005
# 3 0.59 1.71 0.045
# 13 0.84 2.31 0.018
# 17 -0.78 -2.04 0.041
# 34 0.96 2.56 0.011
# Quadrant assignment (Anselin 1995 convention):
# HH = 6 LL = 11 HL = 1 LH = 2 NS = 29 (n = 49)
| การเปรียบเทียบComparison | ขนาดข้อมูลSample size | Cohen's κ | ความต่างสูงสุดMax difference | สถานะStatus |
|---|---|---|---|---|
| DAPH ↔ R spdep | n = 49 (Columbus) | 1.000 | < 1e−6 | ✓ PASS |
| DAPH ↔ R spdep | n = 928 (TB-2021) | 1.000 | < 1e−6 | ✓ PASS |
κ = 1.0 หมายถึง cluster assignment ตรงทุก location · "ความต่างสูงสุด" คือ ค่าผิดพลาดสูงสุดของ local I ที่ไหนสักแห่งใน dataset.κ = 1.0 means cluster labels agree at every location · "Max difference" is the maximum location-wise error of local I anywhere in the dataset.
4การแปลผลและตัวอย่างInterpretation and Example
4 quadrant ตาม Anselin 1995:
① HH (สีแดงเข้ม) — พื้นที่นี้และเพื่อนบ้านมีค่าสูงทั้งคู่ → hot cluster ที่ควรเฝ้าระวัง
② LL (สีน้ำเงินเข้ม) — ทั้งคู่ต่ำ → cold cluster
③ HL (สีชมพู) — ตัวเองสูง เพื่อนบ้านต่ำ → outlier ที่อาจเป็น "เกาะร้อนกลางพื้นที่ปลอดภัย" (ควรสอบสวน)
④ LH (สีฟ้าอ่อน) — ตัวเองต่ำ เพื่อนบ้านสูง → outlier (ทำไมที่นี่ปลอดภัย ทั้งที่รอบข้างไม่ปลอดภัย?)
⑤ NS (เทา) — ไม่มีนัยสำคัญที่ p < .05
The 4 Anselin (1995) quadrants:
① HH (dark red) — both this place and its neighbours are high → hot cluster worth surveillance
② LL (dark blue) — both low → cold cluster
③ HL (pink) — high surrounded by lows → outlier, possibly a "hot island in a safe area" (investigate)
④ LH (light blue) — low surrounded by highs → outlier (why is this one safe when surroundings are not?)
⑤ NS (grey) — not significant at p < .05
📖 References
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27(2), 93–115. doi:10.1111/j.1538-4632.1995.tb00338.x
- Moran, P. A. P. (1950). Notes on continuous stochastic phenomena. Biometrika, 37(1/2), 17–23. doi:10.1093/biomet/37.1-2.17
- Anselin, L. (1996). The Moran scatterplot as an ESDA tool to assess local instability in spatial association. In M. Fischer et al. (eds.) Spatial Analytical Perspectives on GIS, pp. 111–125. London: Taylor & Francis.
- Bivand, R. S., & Wong, D. W. S. (2018). Comparing implementations of global and local indicators of spatial association. TEST, 27(3), 716–748. doi:10.1007/s11749-018-0599-x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.5 LISA Bivariate — Local Moran's I_xy
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Bivariate Local Moran's I ขยาย LISA ให้ตรวจ ความสัมพันธ์เชิงพื้นที่ระหว่างตัวแปร 2 ตัว — ค่า x ที่พื้นที่ i กับค่า y ของเพื่อนบ้าน. ใช้แทน "correlation" แบบที่นับ across-unit ตรงไปตรงมาในกรณีที่ทั้งสองตัวแปรอาจมี spatial autocorrelation ของตัวเอง. พัฒนาโดย Anselin, Syabri & Smirnov (2002).
Bivariate Local Moran's I extends LISA to detect spatial co-variation between two variables — value of x at location i versus value of y in its neighbourhood. It replaces naïve cross-unit correlation when both variables have their own spatial autocorrelation. Introduced by Anselin, Syabri & Smirnov (2002).
2หลักการและสูตรLogic and Formula
กำหนดให้ z_i^x และ z_i^y เป็นค่า standardise ของ x และ y, w_ij = น้ำหนักเชิงพื้นที่:
Let z_i^x and z_i^y be standardised x and y, with w_ij the spatial weight:
- I_i^{xy}
- bivariate local I — ความสัมพันธ์ของ x ที่ i กับ y ของเพื่อนบ้านbivariate local I — co-variation of x at i with y in neighbours
- z_i^x
- x ที่ standardise ที่พื้นที่ istandardised x at i
- z_j^y
- y ที่ standardise ที่เพื่อนบ้าน jstandardised y at neighbour j
p-value ใช้ permutation test เหมือน Univariate LISA — สุ่ม z_j^y 999 ครั้ง (คงค่า z_i^x ไว้) แล้ววัดสัดส่วน |I_perm| ≥ |I_obs|.
The p-value uses the same conditional permutation as Univariate LISA — permute z_j^y 999 times (holding z_i^x fixed) and measure the proportion of |I_perm| ≥ |I_obs|.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
หมายเหตุ: R package spdep ไม่มี Bivariate LISA สำเร็จรูป — ผู้ใช้ R สามารถคำนวณด้วยตนเองโดยใช้ spdep::lag.listw เพื่อหา spatial lag ของ y แล้วคูณกับ x ในรูปแบบ standardised values.
Note: R's spdep doesn't ship Bivariate LISA out of the box — R users can compute it manually with spdep::lag.listw for the spatial lag of y multiplied by standardised x.
library(spdep); library(spData)
data(columbus); listw <- nb2listw(read.gal(
system.file("etc/weights/columbus.gal", package="spData")), style="W")
# Standardise CRIME and HOVAL
zx <- scale(columbus$CRIME)
zy <- scale(columbus$HOVAL)
# Lag of zy
lag_zy <- lag.listw(listw, zy)
# Bivariate Local Moran's I — observed
Ixy_obs <- zx * lag_zy
# Permutation p-value (1 location at a time, here we show vectorised)
set.seed(12345)
B <- 999
perm <- replicate(B, {
zy_p <- sample(zy) # permute y
zx * lag.listw(listw, zy_p) # bivariate I under H0
})
p <- rowMeans(abs(perm) >= abs(Ixy_obs))
head(data.frame(POLYID=1:length(zx), Ixy=Ixy_obs, p=p))
| การเปรียบเทียบComparison | n | Cohen's κ | ความต่างสูงสุดMax difference | สถานะStatus |
|---|---|---|---|---|
| DAPH ↔ R manual | 49 (Columbus) | 0.984 | < 0.02 | ✓ PASS* |
* ความแตกต่างเล็กน้อยจาก R manual เกิดจาก permutation seed ของ sample() ใน R ที่สุ่มต่างจาก seed=12345 ที่ DAPH ใช้ — ค่า I_i เองตรงทุกหลัก เพียงแต่จำนวน HH/LL cluster ที่ถูก flag significant อาจต่างกัน 1-2 จุดจากความ random ของ permutation.* The small gap from R manual is because R's sample() uses a different RNG path than DAPH's seed=12345 — the I_i values themselves match exactly; only 1–2 borderline-p locations may flip significance flag due to permutation randomness.
4การแปลผลและตัวอย่างInterpretation and Example
ใช้ quadrant แบบเดียวกับ Univariate แต่ความหมายต่างออกไป:
① HH: x สูงที่นี่ + y สูงรอบๆ → "x ที่นี่ขับเคลื่อน y ของเพื่อนบ้าน"
② LL: x ต่ำที่นี่ + y ต่ำรอบๆ
③ HL: x สูงที่นี่ + y ต่ำรอบๆ → ความขัดแย้ง (อาจเป็น factor ที่ไม่ได้สื่อให้เพื่อนบ้าน)
④ LH: x ต่ำที่นี่ + y สูงรอบๆ
Quadrants are the same as Univariate but mean different things:
① HH: high x here + high y around → "x here drives y in neighbours"
② LL: low x here + low y around
③ HL: high x here + low y around → discordant (maybe x doesn't reach neighbours)
④ LH: low x here + high y around
📖 References
- Anselin, L., Syabri, I., & Smirnov, O. (2002). Visualizing multivariate spatial correlation with dynamically linked windows. In New Tools for Spatial Data Analysis: Proceedings of the Specialist Meeting (CSISS). Santa Barbara, CA. (Conference proceedings.)
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27(2), 93–115. doi:10.1111/j.1538-4632.1995.tb00338.x
- Anselin, L. (2019). A local indicator of multivariate spatial association: extending Geary's c. Geographical Analysis, 51(2), 133–150. doi:10.1111/gean.12164
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.6 Getis-Ord — Global G, Local G_i, G*_i (Hotspot trio)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Getis-Ord statistics เป็นการตรวจ hotspot ตามความเข้มข้นของค่า (concentrations of value) — แตกต่างจาก Moran's I ที่ตรวจ ความคล้ายกัน ทั้งสูงและต่ำ. มี 3 สถิติคู่กัน: Global G (รวมทั้ง dataset), Local G_i (เฉพาะ neighbour ของ i), และ Local G*_i (รวม i เองด้วย). พัฒนาโดย Getis & Ord (1992) และ Ord & Getis (1995). ใช้แพร่หลายในการระบุจุดร้อน/จุดเย็นของโรคใน epidemiology — ค่า G ที่ใหญ่และเป็นบวก = hotspot, ใหญ่และเป็นลบ = coldspot.
Getis-Ord statistics detect concentrations of value magnitude — distinct from Moran's I which detects similarity (both high or both low). The trio: Global G (whole dataset), Local G_i (neighbours of i), and Local G*_i (neighbours plus i). Introduced by Getis & Ord (1992) and Ord & Getis (1995). Widely used in disease epidemiology to identify hotspots/coldspots — large positive G = hotspot, large negative G = coldspot.
2หลักการและสูตรLogic and Formula
- w_ij(d)
- spatial weight ภายในระยะ d (binary หรือ inverse-distance)spatial weight within distance d (binary or inverse-distance)
- w*_ij(d)
- weight ที่รวม i ↔ i เอง (self-weight)weight that includes self (i ↔ i)
- x_i
- ค่าตัวแปร ณ พื้นที่ i (ไม่ standardise)raw variable at i (not standardised)
ค่า G แปลความหมายผ่าน z-score:
Significance is read via the z-score:
— z > +1.96 → hotspot (p < .05)
— z < −1.96 → coldspot (p < .05)
— |z| < 1.96 → ไม่มีนัยสำคัญ
— z > +1.96 → hotspot (p < .05)
— z < −1.96 → coldspot (p < .05)
— |z| < 1.96 → not significant
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
spdeplibrary(spdep); library(spData)
data(columbus)
nb <- read.gal(system.file("etc/weights/columbus.gal", package="spData"))
# Distance-based weights for Getis-Ord (queen contiguity also works)
listw <- nb2listw(nb, style = "B") # binary
listws <- nb2listw(include.self(nb), style="B") # for G* (self-included)
# Global G
globalG.test(columbus$CRIME, listw)
# expect: G = 0.0098, z = 1.86, p = 0.031 (one-sided)
# Local G_i (excludes i)
gi <- localG(columbus$CRIME, listw)
# Local G*_i (includes i)
gis <- localG(columbus$CRIME, listws)
head(data.frame(POLYID=1:length(gi), Gi=as.numeric(gi), Gi_star=as.numeric(gis)))
# Global G: G = 0.00978, z = 1.864, p = 0.031 (one-sided positive)
# Local G_i — top hotspots (z > 1.96):
# POLYID 1 Gi*=2.31, z=2.74, p=0.006 → hotspot
# POLYID 34 Gi*=1.85, z=2.31, p=0.010 → hotspot
# POLYID 17 Gi*=-1.74, z=-2.05, p=0.040 → coldspot
| สถิติStatistic | R (spdep) | DAPH | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|
| Global G (TB-2021) | 0.005237 | 0.005237 | < 1e−6 | ✓ PASS |
| Global G z-score | 2.413 | 2.413 | < 1e−6 | ✓ PASS |
| Local G_i — cluster labels | n=928 | n=928 (κ=1.0) | 0 mismatch | ✓ PASS |
| Local G*_i — cluster labels | n=928 | n=928 (κ=1.0) | 0 mismatch | ✓ PASS |
| ความต่างสูงสุดของ G_iMax difference in G_i | — | < 1e−6 | — | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
การเลือกใช้ G_i เทียบกับ G*_i:
— G_i ตรวจว่า "เพื่อนบ้านของ i มีค่าสูงผิดปกติไหม" — ตัวเองไม่นับ
— G*_i ตรวจว่า "พื้นที่ i รวมเพื่อนบ้านมีค่าสูงผิดปกติไหม" — รวมตัวเอง
โดยทั่วไป G*_i ใช้บ่อยกว่า เพราะตอบคำถาม policy ตรงกว่า ("ตำบลนี้เป็น hotspot ไหม") · DAPH ออกผลทั้งคู่ให้.
G_i vs G*_i — which to use:
— G_i: "are i's neighbours unusually high?" — excludes i itself
— G*_i: "is the i+neighbours area unusually high?" — includes i
G*_i is preferred in most policy applications ("is this sub-district a hotspot?"). DAPH reports both.
📖 References
- Getis, A., & Ord, J. K. (1992). The analysis of spatial association by use of distance statistics. Geographical Analysis, 24(3), 189–206. doi:10.1111/j.1538-4632.1992.tb00261.x
- Ord, J. K., & Getis, A. (1995). Local spatial autocorrelation statistics: distributional issues and an application. Geographical Analysis, 27(4), 286–306. doi:10.1111/j.1538-4632.1995.tb00912.x
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27(2), 93–115. doi:10.1111/j.1538-4632.1995.tb00338.x
- Bivand, R. S., & Wong, D. W. S. (2018). Comparing implementations of global and local indicators of spatial association. TEST, 27(3), 716–748. doi:10.1007/s11749-018-0599-x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
6.7การเลือก Spatial Weights (Queen · Queen ปรับ · Distance band · KNN)GUIDE
1ทำไมการเลือก weights ถึงสำคัญที่สุดWhy the weights choice matters most
ทุกสถิติในบทนี้เริ่มจากเมทริกซ์ W ที่บอกว่า "พื้นที่ไหนเป็นเพื่อนบ้านกับพื้นที่ไหน" · ถ้า W เปลี่ยน ค่า ρ, λ, Moran's I และข้อสรุปก็เปลี่ยนตาม ดังนั้น ต้องรายงานชนิดของ weights ที่ใช้เสมอ — DAPH พิมพ์บรรทัดนี้ให้อัตโนมัติทั้งใน Tab3 และไฟล์ Word
Every statistic in this chapter starts from a matrix W that declares which areas are neighbours. Change W and ρ, λ, Moran's I and the conclusion change with it, so the weights specification must always be reported — DAPH prints that line automatically in Tab3 and in the Word file.
2ตัวเลือกที่มีให้ และควรใช้เมื่อไรThe options, and when to use each
| ตัวเลือกOption | นิยามเพื่อนบ้านNeighbour definition | เหมาะกับUse when |
|---|---|---|
| Queen Contiguity | พื้นที่ที่มีพรมแดนหรือมุมติดกันareas sharing a border or a corner | ข้อมูลระดับจังหวัด/อำเภอที่ต่อกันเป็นผืนเดียวadministrative areas that form one contiguous landmass |
| Queen Contiguity (ปรับ — เชื่อมเกาะ) | เหมือน Queen แต่พื้นที่ที่ไม่มีพรมแดนติดใครเลย (เกาะ) จะถูกเชื่อมกับพื้นที่ที่ใกล้ที่สุดQueen, plus every island is linked to its nearest area | แผนที่ที่มีเกาะ เช่นแผนที่ประเทศไทยที่มีภูเก็ต — Queen ปกติจะทิ้งภูเก็ตไว้โดยไม่มีเพื่อนบ้าน ทำให้ W ขาดออกเป็นสองก้อนmaps containing islands — plain Queen leaves them with no neighbour, which splits W into disconnected groups |
| Distance band | พื้นที่ที่จุดศูนย์กลางห่างกันไม่เกินรัศมีที่กำหนด (ว่างไว้ = โปรแกรมเลือกรัศมีที่เล็กที่สุดที่ทุกพื้นที่มีเพื่อนบ้านอย่างน้อย 1)centroids within a radius (blank = the smallest radius that gives every area ≥ 1 neighbour) | ต้องการให้ระยะทางจริงเป็นตัวกำหนด ไม่ใช่รูปร่างของเขตปกครองwhen real distance, not administrative shape, defines proximity |
| K-Nearest Neighbors | เพื่อนบ้านที่ใกล้ที่สุด k แห่งthe k closest areas | ต้องการให้ทุกพื้นที่มีจำนวนเพื่อนบ้านเท่ากัน · หมายเหตุ: W แบบนี้ไม่สมมาตร ตัวประมาณค่าบางตัว (RE-Error) จึงใช้ไม่ได้when every area should have the same number of neighbours · note: this W is asymmetric, so some estimators (RE-Error) cannot use it |
3คำเตือน "เชื่อมกันไม่ครบ" หมายความว่าอย่างไรWhat the "not fully connected" warning means
ถ้า weights ที่เลือกทำให้แผนที่แตกออกเป็นหลายก้อนที่ไม่มีเพื่อนบ้านร่วมกัน DAPH จะต่อท้ายบรรทัด spatial weights ว่า "⚠ เชื่อมกันไม่ครบ: แยกเป็น N กลุ่ม…" · กรณีนี้เมทริกซ์ W จะมีค่า eigenvalue เท่ากับ 1 หลายค่า ทำให้ พารามิเตอร์เชิงพื้นที่ถูกระบุค่าได้อ่อน — ค่า ρ ที่ได้อาจต่างจากโปรแกรมอื่นเกิน 10% และตัวประมาณค่าแบบ RE-Error อาจไม่ลู่เข้าเลย · ทางแก้: เปลี่ยนเป็น "Queen ปรับ" (ถ้าสาเหตุคือเกาะ) หรือขยายรัศมี หรือใช้ KNN
If the chosen weights split the map into groups with no shared neighbour, DAPH appends "⚠ not fully connected: N separate groups…" to the weights line. W then carries a unit eigenvalue per group, so the spatial parameter is weakly identified — ρ can differ from another program by more than 10%, and the RE-Error estimator may fail to converge. Fix: switch to the modified Queen (if islands are the cause), widen the radius, or use KNN.
ถ้าเกาะอยู่ไกลเกินกว่าจะถือเป็นเพื่อนบ้านจริง ให้กรอกรัศมีสูงสุดที่ยอมรับได้ในช่อง threshold — เกาะที่ไกลกว่านั้นจะไม่ถูกเชื่อม และโปรแกรมจะระบุชื่อพร้อมระยะทางไว้ในรายงาน
If an island is genuinely too far to count as a neighbour, enter the largest acceptable radius in the threshold box — islands beyond it stay unlinked and the report names them with their distance.
4เอกสารอ้างอิงReferences
- Anselin, L. (1988). Spatial Econometrics: Methods and Models. Dordrecht: Kluwer Academic Publishers.
- Getis, A., & Aldstadt, J. (2004). Constructing the spatial weights matrix using a local statistic. Geographical Analysis, 36(2), 90–104. doi:10.1111/j.1538-4632.2004.tb01127.x
6.7 Distribution Map — Choropleth + KDE Heatmap
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Distribution Map ใน DAPH รวม 2 เทคนิคการ visualize ตัวแปรเชิงพื้นที่: Choropleth (แบ่งสีตามคลาส) และ KDE Heatmap (Kernel Density Estimation บนพิกัด point data). Choropleth ใช้แบ่ง polygon เป็นกลุ่มสี — DAPH รองรับ 4 วิธีหลัก: Quantile, Equal Interval, Natural Breaks (Jenks 1967), และ Standard Deviation. KDE Heatmap ใช้ smooth point data ออกเป็น density surface ตามสูตร Silverman (1986).
Distribution Map in DAPH bundles two spatial-visualization techniques: Choropleth (colour by class) and KDE Heatmap (Kernel Density Estimation on point data). Choropleth partitions polygons into colour classes — DAPH supports 4 schemes: Quantile, Equal Interval, Natural Breaks (Jenks 1967), and Standard Deviation. KDE Heatmap smooths point data into a density surface per Silverman (1986).
2หลักการและสูตรLogic and Formula
- K
- จำนวน class ที่กำหนด (เช่น 5)number of classes (e.g. 5)
- c_k
- ค่าตัด (break points)break points
- x̄_k
- ค่าเฉลี่ยของ class kmean of class k
- SDCM
- Sum of squared Deviations from Class MeanSum of squared Deviations from Class Mean
- s
- จุด (x, y) ที่ประเมิน densityevaluation point (x, y)
- K(·)
- kernel function (Gaussian)kernel function (Gaussian)
- h_x, h_y
- bandwidth ในแต่ละแกน (Silverman default)bandwidth per axis (Silverman default)
- n
- จำนวน pointnumber of points
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
classInt + KDE via KernSmoothlibrary(classInt); library(spData); library(KernSmooth)
data(columbus)
x <- columbus$CRIME
# Quantile (5 classes)
ci_q <- classIntervals(x, n = 5, style = "quantile")
# Equal Interval
ci_e <- classIntervals(x, n = 5, style = "equal")
# Natural Breaks (Jenks 1967)
ci_j <- classIntervals(x, n = 5, style = "jenks")
# Standard Deviation
ci_sd <- classIntervals(x, n = 5, style = "sd")
print(ci_q$brks); print(ci_e$brks); print(ci_j$brks); print(ci_sd$brks)
# KDE on point data (e.g. CRIME centroid coordinates)
xy <- coordinates(columbus[, c("X","Y")])
kde <- bkde2D(xy, bandwidth = c(dpik(xy[,1]), dpik(xy[,2])))
# Quantile: 0.18 15.4 26.0 38.2 54.8 68.9
# Equal Interval: 0.18 13.9 27.7 41.4 55.2 68.9
# Jenks: 0.18 15.0 28.4 42.4 55.6 68.9
# Std Dev (μ=35.1, σ=16.7):
# 0.18 18.4 26.7 35.1 43.4 51.7 68.9 (7 breaks for ±2σ scheme)
classInt และ R KernSmoothcomputes class breaks (Quantile / Equal Interval / Natural Breaks / Standard Deviation) + KDE Gaussian kernel with Silverman bandwidth — matches R classInt and R KernSmooth| วิธีMethod | R classInt break #3 | DAPH break #3 | ความต่างDifference | สถานะStatus |
|---|---|---|---|---|
| Quantile | 26.0142 | 26.0142 | < 1e−6 | ✓ PASS |
| Equal Interval | 27.7100 | 27.7100 | < 1e−6 | ✓ PASS |
| Natural Breaks (Jenks) | 28.4220 | 28.4220 | < 1e−6 | ✓ PASS |
| Standard Deviation | 35.1280 (μ) | 35.1280 (μ) | < 1e−6 | ✓ PASS |
Jenks algorithm ของ DAPH ใช้สูตร Fisher-Jenks (1958) ที่เป็นรูป optimal ทางคณิตศาสตร์ — ผลตรงกับ R classInt v0.4-x ทุกหลัก.DAPH's Jenks uses the Fisher-Jenks (1958) algorithm which is mathematically optimal — exact agreement with R classInt v0.4-x.
4การแปลผลและตัวอย่างInterpretation and Example
เลือกวิธี classify อย่างไร:
— Quantile — แต่ละ class มีจำนวน area เท่ากัน · เหมาะกับการเปรียบเทียบลำดับ (rank)
— Equal Interval — ช่วงค่าตัดเท่ากัน · เหมาะเมื่อข้อมูลกระจายเกือบ uniform
— Natural Breaks (Jenks) — ลด within-class variance · เหมาะกับ data ที่มี cluster ตามธรรมชาติ (default ของ DAPH)
— Standard Deviation — แบ่งตาม ±σ จากค่าเฉลี่ย · เหมาะเมื่อข้อมูลเป็น Normal และต้องการเน้น outlier
Choosing a classification scheme:
— Quantile — equal count per class · best for ranking comparisons
— Equal Interval — equal range per class · best when data are roughly uniform
— Natural Breaks (Jenks) — minimises within-class variance · best when data have natural clusters (DAPH default)
— Standard Deviation — split by ±σ around the mean · best for Normally distributed data emphasising outliers
📖 References
- Jenks, G. F. (1967). The data model concept in statistical mapping. International Yearbook of Cartography, 7, 186–190.
- Fisher, W. D. (1958). On grouping for maximum homogeneity. Journal of the American Statistical Association, 53(284), 789–798. doi:10.1080/01621459.1958.10501479
- Silverman, B. W. (1986). Density Estimation for Statistics and Data Analysis. London: Chapman & Hall. ISBN 978-0-412-24620-3.
- Slocum, T. A., McMaster, R. B., Kessler, F. C., & Howard, H. H. (2009). Thematic Cartography and Geovisualization (3rd ed.). Upper Saddle River, NJ: Pearson Prentice Hall. ISBN 978-0-13-229834-6.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 7 — Machine Learning ComparisonChapter 7 — Machine Learning Comparison ✓ Verified
โมดูล ML ของ DAPH แบ่งตาม ลักษณะของตัวแปรตาม 3 ประเภท — Binary (เช่น เป็น/ไม่เป็นโรค), Multiclass (≥3 หมวด เช่น ชนิดเชื้อ), และ Continuous (ค่าตัวเลขต่อเนื่อง เช่น HbA1c). แต่ละ outcome ใช้ metric, สูตร, และ workflow ที่ต่างกัน แต่รายงานเหมือนกันใน framework TRIPOD+AI 2024 (Collins et al. 2024) — มาตรฐานสากลสำหรับ ML prediction studies. DAPH's ML module is organised by outcome type into three sub-modules — Binary (e.g. disease/no disease), Multiclass (≥3 categories, e.g. pathogen types), and Continuous (numeric outcome, e.g. HbA1c). Each uses outcome-specific metrics, formulas, and workflow, but all report under the TRIPOD+AI 2024 framework (Collins et al. 2024) — the international standard for ML prediction studies.
7.1Binary Classification (event / non-event)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Binary ML ใช้ทำนาย outcome 2 หมวด เช่น เป็น/ไม่เป็นโรค, รอด/ตาย, กลับมานอน รพ./ไม่. DAPH ทดสอบ model หลักทั้งหมดในรอบเดียว — Logistic, Random Forest (Breiman 2001), XGBoost (Chen & Guestrin 2016), SVM (Cortes & Vapnik 1995), KNN, Naive Bayes, MLP — แล้วรายงาน AUC + Brier + F1 + MCC พร้อม 95% CI จาก bootstrap. ใช้ SHAP (Lundberg & Lee 2017) อธิบาย feature importance, และ Decision Curve Analysis (Vickers & Elkin 2006) ประเมิน clinical net benefit.
Binary ML predicts a two-class outcome — disease/no-disease, survived/died, readmitted/not. DAPH tests all major models in one pass — Logistic, Random Forest (Breiman 2001), XGBoost (Chen & Guestrin 2016), SVM (Cortes & Vapnik 1995), KNN, Naive Bayes, MLP — and reports AUC + Brier + F1 + MCC with bootstrap 95% CIs. SHAP (Lundberg & Lee 2017) explains feature importance; Decision Curve Analysis (Vickers & Elkin 2006) measures clinical net benefit.
2หลักการและสูตรLogic and Formula
ideal: α_cal = 0, β_cal = 1 (predicted probability ตรงกับ observed risk)
ideal: α_cal = 0, β_cal = 1 (predicted probability matches observed risk)
- p_t
- threshold probability ที่ใช้ตัดสินใจdecision-threshold probability
- F, S
- เซตของ features ทั้งหมด / subset ที่ไม่รวม jset of all features / subset excluding j
- NB
- net benefit หลังหัก harm จาก false-positivenet benefit after deducting harm from false positives
Workflow: (1) train-test split / cross-validation, (2) tune hyperparameters (Optuna), (3) bootstrap 1,000 ครั้งสำหรับ CI, (4) คำนวณ SHAP + DCA, (5) pairwise DeLong test สำหรับ AUC, (6) ส่งออกตาม TRIPOD+AI 2024.
Workflow: (1) train-test split / CV, (2) Optuna hyperparameter search, (3) 1,000-rep bootstrap CI, (4) SHAP + DCA, (5) pairwise DeLong for AUC, (6) export per TRIPOD+AI 2024.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(tidymodels); library(ranger); library(xgboost); library(pROC)
data(BreastCancer, package="mlbench"); bc <- na.omit(BreastCancer)
bc$Class <- factor(bc$Class)
split <- initial_split(bc, prop=.7, strata=Class)
# Logistic
lr_fit <- logistic_reg() %>% set_engine("glm") %>%
fit(Class ~ . - Id, data=training(split))
# Random Forest
rf_fit <- rand_forest(trees=500) %>% set_engine("ranger") %>%
set_mode("classification") %>% fit(Class ~ . - Id, data=training(split))
# AUC on test set + DeLong pairwise test
p_lr <- predict(lr_fit, testing(split), type="prob")$.pred_malignant
p_rf <- predict(rf_fit, testing(split), type="prob")$.pred_malignant
roc_lr <- roc(testing(split)$Class, p_lr); roc_rf <- roc(testing(split)$Class, p_rf)
auc(roc_lr); auc(roc_rf)
roc.test(roc_lr, roc_rf, method="delong")
| Quantity | R (tidymodels / pROC) | DAPH | Status |
|---|---|---|---|
| Logistic AUC | match to 1e−3 | match | ✓ PASS |
| Random Forest AUC | match to 1e−2 | match (RNG seeded) | ✓ PASS |
| DeLong p | match to 1e−4 | match | ✓ PASS |
| SHAP top-3 features | same ranking | same | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
การเลือก "best model" ไม่ใช่แค่ AUC สูงสุด — ต้องดู (1) discrimination (AUC, F1, MCC), (2) calibration (Brier, intercept/slope), (3) clinical utility (DCA net benefit ที่ threshold ที่ใช้จริง), (4) interpretability (SHAP). บางครั้ง Logistic ที่ explain ง่ายและ calibrate ดีกว่า ถูกเลือกใช้ในคลินิกแม้ AUC ต่ำกว่า XGBoost เล็กน้อย.
Choosing the "best model" isn't just AUC — consider (1) discrimination (AUC, F1, MCC), (2) calibration (Brier, intercept/slope), (3) clinical utility (DCA net benefit at the operating threshold), (4) interpretability (SHAP). A well-calibrated explainable Logistic may be preferred clinically over a higher-AUC XGBoost.
📖 References
- Breiman, L. (2001). Random forests. Machine Learning, 45(1), 5–32. doi:10.1023/A:1010933404324
- Chen, T., & Guestrin, C. (2016). XGBoost: A scalable tree boosting system. Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD '16), 785–794. doi:10.1145/2939672.2939785
- Cortes, C., & Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297. doi:10.1007/BF00994018
- Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. Advances in Neural Information Processing Systems (NeurIPS), 30, 4765–4774.
- Vickers, A. J., & Elkin, E. B. (2006). Decision curve analysis: a novel method for evaluating prediction models. Medical Decision Making, 26(6), 565–574. doi:10.1177/0272989X06295361
- Fawcett, T. (2006). An introduction to ROC analysis. Pattern Recognition Letters, 27(8), 861–874. doi:10.1016/j.patrec.2005.10.010
- Collins, G. S., Moons, K. G. M., Dhiman, P., Riley, R. D., Beam, A. L., Van Calster, B., et al. (2024). TRIPOD+AI statement. BMJ, 385, e078378. doi:10.1136/bmj-2023-078378
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
7.2Multiclass Classification (≥3 unordered categories)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Multiclass ML ใช้เมื่อ outcome มี ≥3 หมวด ไม่มีลำดับ เช่น ชนิดเชื้อสาเหตุ (Bacteria / Virus / Fungal / Parasite), ระดับความรุนแรงในแง่ประเภท (mild type A / moderate type B / severe type C). DAPH รองรับ One-vs-Rest (OvR) และ One-vs-One (OvO) strategies สำหรับ AUC; รายงาน macro/micro/weighted F1, multiclass AUC (Hand & Till 2001), Cohen's κ (Cohen 1960), และ confusion matrix ราย class.
Multiclass ML handles outcomes with ≥3 unordered categories — pathogen type (Bacteria / Virus / Fungal / Parasite), categorical severity (mild type A / moderate type B / severe type C). DAPH supports One-vs-Rest (OvR) and One-vs-One (OvO) AUC strategies; reports macro/micro/weighted F1, multiclass AUC (Hand & Till 2001), Cohen's κ (Cohen 1960), and per-class confusion matrix.
2หลักการและสูตรLogic and Formula
เฉลี่ย AUC ของทุกคู่ class (One-vs-One ทุกแบบ) — robust ต่อ class imbalance
Average AUC over every class pair (One-vs-One) — robust to class imbalance
κ: <0.20 poor, 0.21–0.40 fair, 0.41–0.60 moderate, 0.61–0.80 substantial, >0.80 almost perfect (Landis & Koch 1977)
κ: <0.20 poor, 0.21–0.40 fair, 0.41–0.60 moderate, 0.61–0.80 substantial, >0.80 almost perfect (Landis & Koch 1977)
- K, n_k
- จำนวน class, จำนวน sample ใน class knumber of classes, sample size in class k
- p_o, p_e
- observed / chance agreementobserved / chance agreement
- R_k., R_.k
- ผลรวมแถว/คอลัมน์ k ใน confusion matrixrow / column k sums of the confusion matrix
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(tidymodels); library(ranger); library(yardstick)
data(iris) # 3-class outcome (Species)
split <- initial_split(iris, prop=.7, strata=Species)
rf_fit <- rand_forest(trees=500) %>% set_engine("ranger", probability=TRUE) %>%
set_mode("classification") %>% fit(Species ~ ., data=training(split))
pred <- augment(rf_fit, testing(split))
# Macro / Micro / Weighted F1
f_meas(pred, truth=Species, estimate=.pred_class, estimator="macro")
f_meas(pred, truth=Species, estimate=.pred_class, estimator="micro")
f_meas(pred, truth=Species, estimate=.pred_class, estimator="macro_weighted")
# Multiclass AUC (Hand-Till)
roc_auc(pred, truth=Species, .pred_setosa, .pred_versicolor, .pred_virginica,
estimator="hand_till")
# Cohen's kappa
kap(pred, truth=Species, estimate=.pred_class)
# Confusion matrix
conf_mat(pred, truth=Species, estimate=.pred_class)
| Quantity | R (yardstick) | DAPH | Status |
|---|---|---|---|
| Macro-F1 | match to 1e−3 | match | ✓ PASS |
| Hand-Till AUC | match to 1e−3 | match | ✓ PASS |
| Cohen's κ | match to 1e−4 | match | ✓ PASS |
| Log-loss | match to 1e−4 | match | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
Macro F1 ให้น้ำหนักทุก class เท่ากัน (เหมาะกับ class imbalanced ที่ต้องการให้ class น้อยมีค่า) · Micro F1 = accuracy เมื่อ multiclass · Weighted F1 ถ่วงตาม class size (สะท้อน overall performance). รายงานทั้ง 3 ค่า + Hand-Till AUC + κ + confusion matrix. SHAP สำหรับ multiclass แสดงเป็น matrix |class × feature| ของ mean |SHAP|.
Macro F1 weights every class equally (best for imbalanced classes where minority class matters) · Micro F1 equals accuracy in multiclass · Weighted F1 weights by class size (reflects overall performance). Report all three + Hand-Till AUC + κ + confusion matrix. Multiclass SHAP is reported as a |class × feature| matrix of mean |SHAP|.
📖 References
- Hand, D. J., & Till, R. J. (2001). A simple generalisation of the area under the ROC curve for multiple class classification problems. Machine Learning, 45(2), 171–186. doi:10.1023/A:1010920819831
- Cohen, J. (1960). A coefficient of agreement for nominal scales. Educational and Psychological Measurement, 20(1), 37–46. doi:10.1177/001316446002000104
- Landis, J. R., & Koch, G. G. (1977). The measurement of observer agreement for categorical data. Biometrics, 33(1), 159–174. doi:10.2307/2529310
- Fawcett, T. (2006). An introduction to ROC analysis. Pattern Recognition Letters, 27(8), 861–874. doi:10.1016/j.patrec.2005.10.010
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
7.3Continuous Regression (numeric outcome)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Regression ML ใช้ทำนาย outcome ที่เป็น ตัวเลขต่อเนื่อง เช่น HbA1c, ความดัน, จำนวนวันนอน รพ., ค่าใช้จ่ายรักษา. DAPH รองรับ Linear regression + Ridge (Hoerl & Kennard 1970), LASSO (Tibshirani 1996), Elastic Net (Zou & Hastie 2005), Random Forest Regressor, XGBoost Regressor, SVR (Drucker et al. 1997), KNN Regressor, MLP Regressor — รายงาน RMSE + MAE + R² + MAPE พร้อม bootstrap 95% CI + SHAP feature importance + permutation importance.
Regression ML predicts a continuous numeric outcome — HbA1c, BP, length-of-stay, treatment cost. DAPH supports Linear regression + Ridge (Hoerl & Kennard 1970), LASSO (Tibshirani 1996), Elastic Net (Zou & Hastie 2005), Random Forest Regressor, XGBoost Regressor, SVR (Drucker et al. 1997), KNN Regressor, MLP Regressor — reports RMSE + MAE + R² + MAPE with bootstrap 95% CIs + SHAP feature importance + permutation importance.
2หลักการและสูตรLogic and Formula
L1 penalty บังคับให้ β บางตัว = 0 → variable selection อัตโนมัติ
L1 penalty drives some β to exactly 0 → automatic variable selection
- k
- จำนวน predictornumber of predictors
- λ, λ_1, λ_2
- regularisation strength (เลือกด้วย k-fold CV)regularisation strength (chosen via k-fold CV)
- ȳ
- mean ของ y ใน training setmean of y in the training set
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(tidymodels); library(glmnet); library(ranger); library(xgboost); library(yardstick)
data(Boston, package="MASS") # n=506, medv = continuous outcome
split <- initial_split(Boston, prop=.7)
# Linear / Ridge / Lasso / Elastic Net (glmnet)
lr_fit <- linear_reg() %>% set_engine("lm") %>% fit(medv ~ ., data=training(split))
ridge_fit <- linear_reg(penalty=0.1, mixture=0) %>% set_engine("glmnet") %>%
fit(medv ~ ., data=training(split))
lasso_fit <- linear_reg(penalty=0.1, mixture=1) %>% set_engine("glmnet") %>%
fit(medv ~ ., data=training(split))
en_fit <- linear_reg(penalty=0.1, mixture=0.5) %>% set_engine("glmnet") %>%
fit(medv ~ ., data=training(split))
# Random Forest / XGBoost regressors
rf_fit <- rand_forest(trees=500) %>% set_engine("ranger") %>%
set_mode("regression") %>% fit(medv ~ ., data=training(split))
xgb_fit <- boost_tree(trees=500, tree_depth=6) %>% set_engine("xgboost") %>%
set_mode("regression") %>% fit(medv ~ ., data=training(split))
# Metrics on test set
pred <- augment(xgb_fit, testing(split))
metric_set(rmse, mae, rsq, mape)(pred, truth=medv, estimate=.pred)
| Quantity | R | DAPH | Status |
|---|---|---|---|
| Linear RMSE | match to 1e−3 | match | ✓ PASS |
| Ridge R² | match to 1e−3 | match (same λ) | ✓ PASS |
| LASSO selected vars | same set | same set | ✓ PASS |
| RF / XGBoost RMSE | match to 1e−2 | match (RNG seeded) | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
การเลือก metric ตามบริบท:
— RMSE เหมาะเมื่อ outlier สำคัญ (penalize large error²); ในหน่วยเดียวกับ y
— MAE เหมาะเมื่อ outlier ไม่ต้องการให้มี influence (robust)
— R² วัดสัดส่วน variance ที่อธิบายได้ (0–1) — เหมาะกับการเปรียบเทียบ model
— MAPE เหมาะเมื่อรายงานเป็น % (เช่น cost prediction)
เลือก regression แบบ regularised (Ridge/LASSO/Elastic Net) เมื่อมี multicollinearity หรือ p > n. รายงาน optimal λ จาก k-fold CV + selected variables (LASSO).
Pick metric per context:
— RMSE when outliers matter (penalises large error²); same unit as y
— MAE when outliers shouldn't dominate (robust)
— R² proportion of variance explained (0–1) — best for model comparison
— MAPE for percent reporting (e.g. cost prediction)
Use a regularised model (Ridge/LASSO/Elastic Net) when there is multicollinearity or p > n. Report optimal λ from k-fold CV + selected variables (LASSO).
📖 References
- Hoerl, A. E., & Kennard, R. W. (1970). Ridge regression: biased estimation for nonorthogonal problems. Technometrics, 12(1), 55–67. doi:10.1080/00401706.1970.10488634
- Tibshirani, R. (1996). Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society: Series B, 58(1), 267–288. doi:10.1111/j.2517-6161.1996.tb02080.x
- Zou, H., & Hastie, T. (2005). Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society: Series B, 67(2), 301–320. doi:10.1111/j.1467-9868.2005.00503.x
- Friedman, J. H. (2001). Greedy function approximation: a gradient boosting machine. Annals of Statistics, 29(5), 1189–1232. doi:10.1214/aos/1013203451
- Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.). New York: Springer. ISBN 978-0-387-84857-0.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
7.4Spatial Machine Learning
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Spatial Machine Learning คือ ML แบบ cross-sectional บนข้อมูลรายพื้นที่ (areal data) — ใช้ชุด model, metric และ bootstrap-CI engine เดียวกับ Machine Learning Comparison (7.1–7.3) แล้วเพิ่ม 4 ส่วนเชิงพื้นที่: (1) spatial features — พิกัด centroid ของพื้นที่ (coord_x, coord_y) และ spatial lag W·x ของ predictor เชิงตัวเลข (spatial lag ของตัวแปร categorical นิยามไม่ได้ — DAPH ข้ามพร้อมแจ้งเหตุผลในรายงาน); (2) Spatial Block CV — จัด block ด้วย k-means บน centroid แล้วใช้ block เป็น fold (folds = blocks) เพื่อไม่ให้พื้นที่ข้างเคียงคร่อม fold; (3) Moran's I permutation test (999 รอบ) บน out-of-fold residuals ของ model ที่ดีที่สุด; (4) choropleth maps ของ out-of-fold predictions และ residuals.
Spatial Machine Learning is cross-sectional ML on areal data — the same models, metrics, and bootstrap-CI engine as Machine Learning Comparison (7.1–7.3), plus four spatial additions: (1) spatial features — area-centroid coordinates (coord_x, coord_y) and spatial lags W·x of numeric predictors (the spatial lag of a categorical variable is ill-defined — DAPH skips it with a note in the report); (2) Spatial Block CV — k-means blocks on the centroids become the CV folds (folds = blocks) so neighbouring areas never straddle a fold boundary; (3) a Moran's I permutation test (999 permutations) on the best model's out-of-fold residuals; (4) choropleth maps of out-of-fold predictions and residuals.
2หลักการและสูตรLogic and Formula
ค่าเฉลี่ยถ่วงน้ำหนักของ predictor ในพื้นที่เพื่อนบ้าน — ใช้ spatial weights builder ชุดเดียวกับบทที่ 6
Neighbour-weighted average of a predictor — built with the same spatial-weights builders as Chapter 6
- (cx_i, cy_i)
- พิกัด centroid ของพื้นที่ icentroid coordinates of area i
- e_i
- out-of-fold residual ของพื้นที่ i (ทำนายโดย fold ที่ไม่เห็นพื้นที่นั้น)out-of-fold residual of area i (predicted by a fold that never saw it)
การอ่าน Moran's I บน residuals: ถ้า I มีนัยสำคัญ (permutation p < .05) แปลว่ายังมีโครงสร้างเชิงพื้นที่เหลือใน error — ควรเพิ่ม spatial features หรือเปลี่ยนไปใช้ spatial regression (บทที่ 6).
Reading Moran's I on residuals: a significant I (permutation p < .05) means spatial structure remains in the errors — add spatial features or switch to spatial regression (Chapter 6).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
ใน R, workflow แบบ grouped-CV เชิงพื้นที่ที่เทียบเคียงกันสร้างได้ด้วย R package blockCV + spdep สำหรับ Moran test บน residuals:
In R, the analogous grouped-CV workflow can be built with the blockCV package + spdep for the residual Moran test:
library(blockCV); library(spdep); library(sf)
gdf <- st_read("districts.shp")
# 1) Spatially separated folds (blocks = folds)
folds <- cv_spatial(x = gdf, k = 5)
# 2) Fit any model using the fold ids as CV groups,
# collecting out-of-fold predictions/residuals per area
# 3) Moran's I permutation test on out-of-fold residuals
nb <- poly2nb(gdf, queen = TRUE)
lw <- nb2listw(nb, style = "W", zero.policy = TRUE)
moran.mc(gdf$residual_oof, lw, nsim = 999, zero.policy = TRUE)
| ส่วนประกอบComponent | ทวนสอบที่ใดVerified where | สถานะStatus |
|---|---|---|
| engine fit model + metric + bootstrap CIModel-fitting / metric / bootstrap-CI engine | ตัวเดียวกับที่ทวนสอบแล้วใน Machine Learning Comparison (7.1–7.3)same engine verified in Machine Learning Comparison (7.1–7.3) | ✓ PASS |
| spatial weights builders (queen · distance)Spatial weights builders (queen · distance) | ชุดเดียวกับที่ทวนสอบกับสถิติบทที่ 6 (รอบ distance-metric parity 2026-07-31)same builders verified against the Chapter-6 statistics (distance-metric parity run 2026-07-31) | ✓ PASS |
| Moran's I permutation machineryMoran's I permutation machinery | ชุดเดียวกับที่ทวนสอบในหัวข้อ LISAsame machinery verified in the LISA topic | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
ตัวเลขที่ควรรายงานคือค่า Block-CV ไม่ใช่ random-CV — ช่องว่างระหว่างสองค่านี้บอกระดับ "spatial optimism". อ่านคู่กับ Moran's I บน out-of-fold residuals: ไม่มีนัยสำคัญ = model จับโครงสร้างเชิงพื้นที่ได้แล้ว; มีนัยสำคัญ = เพิ่ม spatial features (coord + W·x) หรือพิจารณา spatial regression (บทที่ 6). Choropleth ของ residuals ช่วยชี้ "ย่านที่ model ทำนายพลาดเป็นระบบ" เพื่อนำไปตั้งสมมุติฐานเชิงพื้นที่ต่อ.
Report the Block-CV number, not random CV — the gap between the two measures the "spatial optimism". Read it together with Moran's I on out-of-fold residuals: non-significant = the model has absorbed the spatial structure; significant = add spatial features (coords + W·x) or consider spatial regression (Chapter 6). The residual choropleth pinpoints neighbourhoods where the model errs systematically, guiding further spatial hypotheses.
📖 References
- Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., et al. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913–929. doi:10.1111/ecog.02881
- Valavi, R., Elith, J., Lahoz-Monfort, J. J., & Guillera-Arroita, G. (2019). blockCV: An R package for generating spatially or environmentally separated folds for k-fold cross-validation of species distribution models. Methods in Ecology and Evolution, 10(2), 225–232. doi:10.1111/2041-210X.13107
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27(2), 93–115. doi:10.1111/j.1538-4632.1995.tb00338.x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
7.5External Validation & Save Model (.daphmodel) + Temporal Split
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Save Model: หลังรัน Machine Learning Comparison / Spatial ML, model ที่ดีที่สุด (fitted preprocessing + estimator + decision threshold ที่ถูกล็อก) บันทึกเป็นไฟล์ .daphmodel ได้ · แบบจำลอง Linear / Logistic / Mixed-Effect Linear regression ก็บันทึกได้เช่นกัน (สำหรับ binary logistic, DAPH คำนวณ Youden threshold บนข้อมูลพัฒนา (development data) แล้วล็อกไว้ในไฟล์).
Save Model: after a Machine Learning Comparison / Spatial ML run, the best model (fitted preprocessing + estimator + the locked decision threshold) can be saved as a .daphmodel file. Linear / Logistic / Mixed-Effect Linear regression models can also be saved (for binary logistic, DAPH computes the Youden threshold on the development data and locks it into the file).
External Validation (แนวทาง TRIPOD): เมื่อโหลดข้อมูลชุดใหม่และแนบไฟล์ model ที่บันทึกไว้, DAPH รันโหมด external-only: model ให้คะแนนข้อมูลใหม่ทั้งชุดที่ threshold ซึ่งล็อกจากข้อมูลพัฒนา — DAPH ไม่ re-optimise threshold บนข้อมูลใหม่เด็ดขาด เพราะเท่ากับ leak ข้อมูล external. รายงานแสดง model card สองด้าน (ฝั่ง development ที่ตรึงไว้ vs ฝั่งข้อมูลใหม่), ตาราง Development-vs-External พร้อม 95% CI ทุกช่อง, และคำวินิจฉัย transportability.
External Validation (TRIPOD workflow): with new data loaded and the saved model attached, DAPH runs an external-only pass: the model scores the entire new dataset at the development-locked threshold — DAPH never re-optimises the threshold on the new data, as that would leak the external set. The report shows a two-sided model card (fixed development side vs new-data side), a Development-vs-External metric table with a 95% CI in every cell, and a transportability verdict.
2หลักการและสูตรLogic and Formula
Δ ≤ 0.05 → transports well · 0.05 < Δ ≤ 0.10 → เสื่อมปานกลาง ควรพิจารณา recalibration · Δ > 0.10 → เสื่อมมาก ควร update/retrain
Δ ≤ 0.05 → transports well · 0.05 < Δ ≤ 0.10 → moderate degradation, consider recalibration · Δ > 0.10 → substantial, update/retrain
- t*
- threshold ที่ล็อกจากข้อมูลพัฒนา — ใช้ค่าเดิมเป๊ะกับข้อมูลใหม่threshold locked on development data — reused verbatim on new data
- M
- headline metric (เช่น AUC สำหรับ binary, R² สำหรับ continuous)headline metric (e.g. AUC for binary, R² for continuous)
- t_(q)
- จุดตัดเชิงเวลา — train คือส่วนแรกสุดตามสัดส่วนที่เลือก, test คือส่วนล่าสุดchronological cut point — train is the earliest fraction, test the most recent
เมื่อไรควรทำ external validation: รายงานผลพัฒนา model หลักของ DAPH จะแนะนำให้ทำ external validation เมื่อช่องว่างระหว่างค่า test กับค่า CV ของ headline metric ≥ 0.07 — สัญญาณว่าประมาณการภายในยังไม่นิ่งพอ. Temporal split เป็นทางเลือกแทน random train/test split: แบ่งตามตัวแปรเวลาโดยไม่สับข้อมูล — train บนส่วนแรกสุด, test บนส่วนล่าสุด — ค่าที่ได้จำลอง "การพยากรณ์ไปข้างหน้า" และรายงานระบุช่วงเวลา + ขนาดตัวอย่างของทั้งสองส่วน (ไม่มี temporal leakage).
When to externally validate: DAPH's main development report recommends external validation when the test-vs-CV gap of the headline metric is ≥ 0.07 — a signal that the internal estimate is not yet stable. Temporal split is the alternative to the random train/test split: split chronologically by a time variable with no shuffling — train on the earliest fraction, test on the most recent — so the held-out estimate simulates forecasting forward in time; the report states both periods and sample sizes (no temporal leakage).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(pROC)
# Development: fit + lock the Youden threshold
fit <- glm(event ~ age + lab1 + lab2, data = dev, family = binomial)
roc_dev <- roc(dev$event, predict(fit, type = "response"))
thr <- coords(roc_dev, "best", best.method = "youden")$threshold # LOCKED
# External validation: score ALL new data at the LOCKED threshold
p_ext <- predict(fit, newdata = external, type = "response")
roc_ext <- roc(external$event, p_ext)
auc(roc_dev); auc(roc_ext) # Delta = dev - ext
table(pred = p_ext >= thr, obs = external$event) # Sens/Spec at locked thr
# Temporal split: train on the earliest 70%, test on the most recent 30%
d <- d[order(d$visit_date), ]
cut <- floor(0.7 * nrow(d))
train <- d[1:cut, ]; test <- d[(cut + 1):nrow(d), ]
| พฤติกรรมที่ทดสอบBehaviour tested | ผลการทดสอบTest result | สถานะStatus |
|---|---|---|
| threshold ที่ล็อกถูกใช้ค่าเดิมเป๊ะบนข้อมูล externalLocked threshold used verbatim on external data | บังคับเปลี่ยน threshold แล้ว sensitivity/specificity เปลี่ยนตามที่คาดforcing a different threshold changes sensitivity/specificity as expected | ✓ PASS |
| temporal split ไม่มี leakageTemporal split has no leakage | จุดตัดเชิงเวลาให้ช่วง test ทั้งหมดอยู่หลังช่วง train เสมอthe chronological cut always places the whole test period after the training period | ✓ PASS |
| การคำนวณ metric (AUC · Brier · Sens/Spec · R² · RMSE · MAE + bootstrap CI)Metric computation (AUC · Brier · Sens/Spec · R² · RMSE · MAE + bootstrap CI) | engine ตัวเดียวกับที่ทวนสอบแล้วใน Machine Learning Comparison (7.1–7.3)same engine verified in Machine Learning Comparison (7.1–7.3) | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
External validation ≠ การ fit ใหม่ — ฝั่ง development ใน model card ถูกตรึงไว้ทั้งหมด (preprocessing, estimator, threshold) ส่วนฝั่งข้อมูลใหม่คือผลการให้คะแนนล้วน ๆ. อ่านตาราง Dev-vs-External ทีละ metric พร้อม CI: discrimination ตก (AUC) มักหมายถึง case-mix ต่างกัน; calibration ตก (Brier) มักแก้ได้ด้วย recalibration โดยไม่ต้อง retrain. คำวินิจฉัย transportability อิงจาก Δ ของ headline metric: Δ ≤ 0.05 ใช้ต่อได้ · 0.05 < Δ ≤ 0.10 พิจารณา recalibration · Δ > 0.10 update/retrain. สำหรับงานที่ข้อมูลสะสมตามเวลา ให้ใช้ temporal split ตั้งแต่ขั้นพัฒนา — ค่าที่รายงานจะสื่อความสามารถ "พยากรณ์อนาคต" ตรงกว่า random split.
External validation ≠ refitting — the development side of the model card is fully frozen (preprocessing, estimator, threshold); the new-data side is pure scoring. Read the Dev-vs-External table metric by metric with CIs: a discrimination drop (AUC) usually reflects a different case-mix; a calibration drop (Brier) is often fixable by recalibration without retraining. The transportability verdict follows the headline-metric drop: Δ ≤ 0.05 keep using · 0.05 < Δ ≤ 0.10 consider recalibration · Δ > 0.10 update/retrain. When data accrue over time, use the temporal split from the development stage — the reported figure then genuinely reflects forecasting ability rather than a random split.
📖 References
- Collins, G. S., Reitsma, J. B., Altman, D. G., & Moons, K. G. M. (2015). Transparent Reporting of a multivariable prediction model for Individual Prognosis Or Diagnosis (TRIPOD): the TRIPOD statement. Annals of Internal Medicine, 162(1), 55–63. doi:10.7326/M14-0697
- Steyerberg, E. W. (2019). Clinical Prediction Models: A Practical Approach to Development, Validation, and Updating (2nd ed.). Cham: Springer. ISBN 978-3-030-16398-3.
- Youden, W. J. (1950). Index for rating diagnostic tests. Cancer, 3(1), 32–35. doi:10.1002/1097-0142(1950)3:1<32::AID-CNCR2820030106>3.0.CO;2-3
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 8 — การวิเคราะห์เส้นทาง (Path Analysis: SEM / GSEM)Chapter 8 — Path Analysis (SEM / GSEM) ✓ Verified
การวิเคราะห์เส้นทาง (Path Analysis) แยกอิทธิพลของตัวแปรต้นที่มีต่อตัวแปรตามออกเป็น อิทธิพลทางตรง (direct), อิทธิพลทางอ้อม (indirect) ผ่านตัวแปรส่งผ่าน (mediator) และ อิทธิพลรวม (total). DAPH เลือกวิธีให้อัตโนมัติตามชนิดตัวแปรตาม — SEM (เชิงเส้น) เมื่อ Y ต่อเนื่อง · GSEM (binary logit) เมื่อ Y สองกลุ่ม · GSEM (ordered logit) เมื่อ Y จัดอันดับ · GSEM (multinomial logit) เมื่อ Y หลายกลุ่มไม่จัดอันดับ — ทั้งสามกรณี categorical อยู่ในตระกูล generalized SEM (gsem) เดียวกัน. อิทธิพลทางอ้อมในกรณีเชิงเส้นใช้สูตรผลคูณสัมประสิทธิ์พร้อม bootstrap CI; เมื่อตัวแปรตามไม่เชิงเส้น ใช้ counterfactual causal mediation (g-formula) ซึ่งเป็นวิธีมาตรฐานที่ยอมรับในวารสารระดับสูง. Path analysis partitions the effect of predictors on an outcome into direct, indirect (through mediators) and total components. DAPH auto-selects the estimator from the outcome's measurement type — SEM (linear) for a continuous Y, GSEM (binary logit) for a two-level Y, GSEM (ordered logit) for an ordinal Y, and GSEM (multinomial logit) for an unordered (nominal) Y — all three categorical cases belong to the same generalized-SEM (gsem) family. Indirect effects in the linear case use the product-of-coefficients method with bootstrap CIs; when the outcome is non-linear, DAPH reports counterfactual causal mediation (the g-formula) — the journal-accepted decomposition under non-collapsibility.
8.1SEM Path Analysis — Continuous Outcome (direct, indirect, total + model fit)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
SEM path analysis ตอบคำถามที่ regression ปกติตอบไม่ได้ — ตัวแปรต้นส่งผลต่อผลลัพธ์ โดยตรง เท่าไร และส่งผ่าน กลไกตัวกลาง เท่าไร. เป็นเครื่องมือหลักของงานวิจัยเชิงทฤษฎีด้านสุขภาพ เช่น การทดสอบว่า "ฐานะทางเศรษฐกิจ → ความรอบรู้ด้านสุขภาพ → คุณภาพชีวิต" — ฐานะส่งผลต่อคุณภาพชีวิตโดยตรง หรือผ่านความรอบรู้ด้านสุขภาพเป็นหลัก. คำตอบกำหนดว่าควรออกแบบ intervention ที่จุดใด.
SEM path analysis answers what ordinary regression cannot — how much of a predictor's effect reaches the outcome directly versus through an intervening mechanism. It is a workhorse of theory-driven health research, e.g. testing "socioeconomic status → health literacy → quality of life": does SES act on QoL directly, or mainly through health literacy? The answer dictates where an intervention should be targeted.
2หลักการและสูตรLogic and Formula
เอกลักษณ์ทางพีชคณิตของ OLS: ผลรวม = สัมประสิทธิ์จากการถดถอย Y บน X เพียงอย่างเดียว (reduced form) — DAPH ตรวจสอบว่าตรงกันถึงระดับความแม่นยำของเครื่อง
OLS algebraic identity: the total equals the coefficient from regressing Y on X alone (reduced form) — DAPH confirms this to machine precision
- a_kj, b_j, c'_k
- สัมประสิทธิ์ X→M, M→Y, และทางตรง X→YX→M, M→Y, and direct X→Y coefficients
- A, Ψ
- เมทริกซ์เส้นทางมีทิศทาง / ความแปรปรวน-ร่วมของส่วนเหลือ+ตัวแปรต้นนอกdirected-path matrix / disturbance + exogenous covariance
- S, Σ̂, p, q
- ความแปรปรวนร่วมที่สังเกต / ที่โมเดลบ่งชี้ / จำนวนตัวแปร / จำนวนพารามิเตอร์อิสระobserved / model-implied covariance / # variables / # free parameters
- χ²₀, df₀
- ของโมเดลฐาน (independence) สำหรับ CFI/TLIbaseline (independence) model, for CFI/TLI
กลไก: DAPH ประมาณค่าด้วยลูกโซ่ของการถดถอย (chain of regressions) — สมการเชิงเส้นแต่ละสมการเทียบเท่ากับการประมาณค่าแบบ ML ของ SEM สำหรับโมเดล recursive แบบสังเกตได้เต็ม จึงให้สัมประสิทธิ์ตรงกับโปรแกรม SEM มาตรฐาน. CI ของอิทธิพลทางอ้อมใช้ percentile bootstrap (ไม่อิงสมมติฐานการแจกแจงปกติของผลคูณ ซึ่งเบ้) ตาม MacKinnon และคณะ (2004).
How it works: DAPH estimates a chain of regressions — for a fully-observed recursive model each linear equation is identical to the SEM ML estimate, so the path coefficients match standard SEM software exactly. Indirect-effect CIs use percentile bootstrapping (the product is skewed, so a normal-theory SE is invalid), following MacKinnon et al. (2004).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(lavaan)
model <- '
M ~ a1*X1 + a2*X2 # mediator equation
Y ~ b*M + cp1*X1 + cp2*X2 # outcome equation (cp = direct effect c prime)
ind1 := a1*b # indirect effect of X1 through M
total1 := cp1 + a1*b # total effect of X1
'
fit <- sem(model, data = df, se = "bootstrap", bootstrap = 1000)
summary(fit, fit.measures = TRUE, ci = TRUE)
# -> path coefficients, indirect/total with bootstrap CIs,
# chi-square, RMSEA, CFI, TLI, SRMR
| Quantity | R (lm / lavaan) | DAPH — measured Δ | Status |
|---|---|---|---|
| Coefficients b + SE (every equation) | lm() | Δ < 1×10⁻¹² | ✓ PASS |
| p-values (t-based) | lm() | Δ < 1×10⁻¹⁴ | ✓ PASS |
| Indirect a·b + total c′+Σa·b | lavaan := a*b | Δ ≤ 1.3×10⁻¹¹ | ✓ PASS |
| Bootstrap 95% CI (B = 1,000) | R percentile boot | Δ ≤ 0.005 (MC error) | ✓ PASS |
| χ² / p / RMSEA / CFI / TLI / SRMR | lavaan fitMeasures() | Δ ≤ 2.1×10⁻⁴ | ✓ PASS |
| logLik / AIC / BIC / R² | lavaan / lm | Δ < 3×10⁻¹¹ | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 (lavaan 0.6.21) บนข้อมูลจำลอง N = 600 — อ่าน CSV ชุดเดียวกันทั้ง Python/R; Δ = ผลต่างสัมบูรณ์สูงสุดที่วัดได้จริง (33 รายการตรวจ)R 4.3.3 (lavaan 0.6.21) on simulated data, N = 600 — Python and R read the identical CSV; Δ = measured maximum absolute difference (33 checks).
4การแปลผลและตัวอย่างInterpretation and Example
เกณฑ์ความกลมกลืน (Hu & Bentler 1999): χ²/df < 3 ยอมรับได้ (< 2 ดีเยี่ยม) · RMSEA < 0.08 ยอมรับได้ (< 0.05 ดีเยี่ยม) · CFI/TLI > 0.90 ยอมรับได้ (> 0.95 ดีเยี่ยม) · SRMR < 0.08. การส่งผ่าน: ถ้าอิทธิพลทางอ้อมมีนัยสำคัญแต่ทางตรงไม่ → การส่งผ่านสมบูรณ์ (full mediation); ถ้านัยสำคัญทั้งคู่ → การส่งผ่านบางส่วน (partial mediation). ตัดสินนัยสำคัญของอิทธิพลทางอ้อมจาก bootstrap CI (ถ้าไม่คร่อม 0 = นัยสำคัญ) ไม่ใช่จาก Sobel test ซึ่งอ่อนไหวต่อความเบ้.
Fit thresholds (Hu & Bentler 1999): χ²/df < 3 acceptable (< 2 excellent) · RMSEA < 0.08 acceptable (< 0.05 excellent) · CFI/TLI > 0.90 acceptable (> 0.95 excellent) · SRMR < 0.08. Mediation: a significant indirect effect with a non-significant direct effect indicates full mediation; both significant indicates partial mediation. Judge the indirect effect from the bootstrap CI (significant if it excludes 0), not the Sobel test, which is sensitive to skew.
📖 References
- Wright, S. (1934). The method of path coefficients. The Annals of Mathematical Statistics, 5(3), 161–215. doi:10.1214/aoms/1177732676
- Bollen, K. A. (1989). Structural Equations with Latent Variables. New York: Wiley. ISBN 978-0-471-01171-2.
- Baron, R. M., & Kenny, D. A. (1986). The moderator–mediator variable distinction in social psychological research. Journal of Personality and Social Psychology, 51(6), 1173–1182. doi:10.1037/0022-3514.51.6.1173
- MacKinnon, D. P., Lockwood, C. M., & Williams, J. (2004). Confidence limits for the indirect effect: distribution of the product and resampling methods. Multivariate Behavioral Research, 39(1), 99–128. doi:10.1207/s15327906mbr3901_4
- Preacher, K. J., & Hayes, A. F. (2008). Asymptotic and resampling strategies for assessing and comparing indirect effects in multiple mediator models. Behavior Research Methods, 40(3), 879–891. doi:10.3758/BRM.40.3.879
- Hu, L., & Bentler, P. M. (1999). Cutoff criteria for fit indexes in covariance structure analysis. Structural Equation Modeling, 6(1), 1–55. doi:10.1080/10705519909540118
- Kline, R. B. (2016). Principles and Practice of Structural Equation Modeling (4th ed.). New York: Guilford Press. ISBN 978-1-4625-2334-4.
- Rosseel, Y. (2012). lavaan: an R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36. doi:10.18637/jss.v048.i02
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
8.2GSEM & Causal Mediation — Binary Outcome (NDE / NIE, odds-ratio scale)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
เมื่อตัวแปรตามเป็น สองกลุ่ม (เป็น/ไม่เป็นโรค) สมการ Y เป็น logit ทำให้สูตรผลคูณสัมประสิทธิ์ ใช้ไม่ได้ — เพราะ odds ratio ไม่ collapsible (การปรับ/ไม่ปรับตัวแปรกลางเปลี่ยนค่า OR แม้ไม่มี confounding). DAPH จึงรายงานอิทธิพลทางอ้อม/รวมด้วย causal mediation แบบ counterfactual — natural direct effect (NDE) และ natural indirect effect (NIE) บนสเกล odds ratio ประมาณด้วย g-formula — เป็นวิธีที่ยอมรับในวารสารระบาดวิทยาชั้นนำ (VanderWeele 2015).
When the outcome is binary (disease/no-disease) the Y equation is a logit, so the product-of-coefficients rule fails — the odds ratio is non-collapsible (adjusting or not for the mediator changes the OR even with no confounding). DAPH instead reports indirect/total effects via counterfactual causal mediation — the natural direct effect (NDE) and natural indirect effect (NIE) on the odds-ratio scale, estimated by the g-formula — the standard accepted in leading epidemiology journals (VanderWeele 2015).
2หลักการและสูตรLogic and Formula
สำหรับ mediator ต่อเนื่องหลายตัว ผลรวมเชิงเส้นของตัวกลางเป็นปกติหลายตัวแปร → อินทิเกรตด้วย Gauss–Hermite โดยคง covariance ของส่วนเหลือ (จัดการ mediator ที่สัมพันธ์กันได้ถูกต้อง)
For several continuous mediators, the mediator linear combination is multivariate-normal → integrated by Gauss–Hermite while preserving the residual covariance (correlated mediators handled correctly)
- Y(x, M(x'))
- ผลลัพธ์เชิงโต้แย้ง: X ตั้งเป็น x แต่ตัวกลางเป็นค่าที่จะเกิดเมื่อ X = x'counterfactual outcome: X set to x while the mediator takes the value it would under X = x'
- p₁₀, p₀₀, p₁₁
- ความน่าจะเป็นเฉลี่ยของสามสถานการณ์ counterfactualpopulation-averaged probabilities of the three counterfactual scenarios
- Σ_ε, b
- covariance ส่วนเหลือของตัวกลาง / เวกเตอร์สัมประสิทธิ์ M→Ymediator residual covariance / vector of M→Y coefficients
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(mediation) # Imai, Keele, Tingley & Yamamoto
m.model <- glm(M ~ X + C, data = df) # mediator model
y.model <- glm(Y ~ X + M + C, family = binomial, data = df) # outcome (logit)
med <- mediate(m.model, y.model, treat = "X", mediator = "M",
robustSE = TRUE, sims = 1000)
summary(med) # ACME (= NIE), ADE (= NDE), total effect, proportion mediated
# Equivalent g-formula with the OR scale (CMAverse):
library(CMAverse)
cmest(data = df, model = "gformula", outcome = "Y", exposure = "X",
mediator = "M", basec = "C", EMint = FALSE,
yreg = "logistic", mreg = list("linear"), astar = 0, a = 1)
| Quantity | R (glm + independent g-formula) | DAPH — measured Δ | Status |
|---|---|---|---|
| Logit b / SE / p (outcome eq.) | glm(binomial) | Δ ≤ 1.3×10⁻¹³ | ✓ PASS |
| Mediator equation b / SE / p | lm() | Δ ≤ 3.6×10⁻¹⁴ | ✓ PASS |
| Binary X coded 1/2 → auto 0/1 | glm with factor(x) | Δ ≤ 8.2×10⁻¹⁴ | ✓ PASS |
| NDE / NIE / Total OR (g-formula) | independent R implementation | Δ ≤ 4.8×10⁻¹³ | ✓ PASS |
| Total = NDE × NIE (identity) | multiplicative | Δ < 1×10⁻¹² | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 บนข้อมูลจำลอง N = 800 (X ต่อเนื่อง + binary 1/2 + nominal 3 กลุ่ม, mediator ต่อเนื่อง) — g-formula ฝั่ง R เขียนขึ้นอิสระจากนิยาม counterfactual แล้วเทียบผลตรงกันถึงระดับ 10⁻¹³R 4.3.3 on simulated data, N = 800 (continuous + 1/2-coded binary + 3-level nominal X, continuous mediator) — the R g-formula was written independently from the counterfactual definitions; agreement to the 10⁻¹³ level.
4การแปลผลและตัวอย่างInterpretation and Example
NDE = ผลของ X ต่อ Y เมื่อ "ตรึง" ตัวกลางไว้ที่ค่าธรรมชาติเมื่อไม่มีการรับ exposure · NIE = ส่วนที่ทำงานผ่านการเปลี่ยนแปลงของตัวกลาง · Total = NDE × NIE (สเกล OR). ค่าทั้งหมดเป็น odds ratio ที่เทียบ X = 0 กับ X = 1 (สำหรับตัวแปรต่อเนื่องคือ OR ต่อการเพิ่ม 1 หน่วย). ข้อสมมติเชิงสาเหตุ: การตีความว่าเป็น "สาเหตุ" ต้องไม่มีตัวแปรกวนที่ไม่ได้วัดระหว่าง exposure–outcome, mediator–outcome และ exposure–mediator (VanderWeele 2015) — DAPH ระบุข้อสมมตินี้ไว้ในหมายเหตุของรายงานทุกครั้ง. หลายตัวกลาง: เมื่อตัวแปรต้นมีตัวกลาง ≥ 2 ตัว DAPH รายงานทั้ง อิทธิพลทางอ้อมรายตัวกลาง (interventional NIE ผ่านแต่ละตัว) และ อิทธิพลทางอ้อมรวม (joint NIE ผ่านทั้งชุด); เนื่องจากผลรายตัวกลางอาจซ้อนทับกัน จึงไม่จำเป็นต้องคูณกันได้พอดีเท่ากับผลรวม (Vansteelandt & Daniel 2017). ตัวกลางที่เป็น categorical (เช่น กลุ่ม BMI) นับเป็น ตัวกลางเดียว เสมอ (รวมทุกระดับ).
NDE = X's effect on Y with the mediator held at the value it would naturally take under no exposure · NIE = the portion working through a change in the mediator · Total = NDE × NIE (OR scale). All are odds ratios contrasting X = 0 vs X = 1 (for a continuous predictor, the OR per one-unit increase). Causal assumptions: a causal reading requires no unmeasured exposure–outcome, mediator–outcome or exposure–mediator confounding (VanderWeele 2015) — DAPH states this assumption in every report's note. Multiple mediators: when a predictor has two or more mediators, DAPH reports both the mediator-specific indirect effect (the interventional NIE through each mediator) and the combined indirect effect (the joint NIE through the whole set); because the mediator-specific effects can overlap, they need not multiply exactly to the combined effect (Vansteelandt & Daniel 2017). A categorical mediator (e.g., BMI group) always counts as a single mediator (all its levels together).
สเกลของผลถูกกำหนดโดย “ตัวแปรตาม” เสมอ ไม่ใช่ตัวส่งผ่านหรือตัวแปรต้น: เพราะสมการ Y เป็น logit ผลทุกชนิด — ทางตรง (NDE) · ทางอ้อมรายตัวส่งผ่าน (NIE ผ่านแต่ละตัว) · ทางอ้อมรวม (joint NIE) · และรวม (Total) — จึงรายงานเป็น odds ratio ทั้งหมด. ชนิดของ ตัวแปรส่งผ่าน และ ตัวแปรต้น ไม่เปลี่ยนเรื่องนี้: ตัวส่งผ่านที่เป็น ต่อเนื่อง (เช่น BMI) เพียงทำให้ g-formula ต้องอินทิเกรตทับการแจกแจงต่อเนื่องของมัน แต่ผลลัพธ์ยังเป็น OR (ผลต่อ odds ของ Y); ตัวแปรต้นที่เป็น ต่อเนื่อง (เช่น Age) ก็ให้ OR ต่อการเพิ่ม 1 หน่วยเช่นกัน. จะได้ค่าเป็น β (ผลต่าง) ก็ต่อเมื่อ ตัวแปรตาม เป็นต่อเนื่อง (SEM เชิงเส้น, ดู §8.1) เท่านั้น. และเพราะเป็นสเกลอัตราส่วน การแตกส่วนจึงเป็นแบบ คูณ (Total OR = Direct OR × Indirect OR) ไม่ใช่ บวก อย่างในกรณีเชิงเส้น.
The scale is always set by the OUTCOME — not by the mediator or the predictor: because the Y equation is a logit, every effect — direct (NDE), mediator-specific indirect (the NIE through each mediator), combined (joint NIE), and total — is reported as an odds ratio. The type of the mediator or the predictor does not change this: a continuous mediator (e.g., BMI) merely makes the g-formula integrate over its continuous distribution, yet the result is still an OR (an effect on the odds of Y); a continuous predictor (e.g., Age) likewise yields an OR per one-unit increase. Effects appear on the β (difference) scale only when the outcome itself is continuous (linear SEM, see §8.1). Being a ratio scale, the decomposition is multiplicative (Total OR = Direct OR × Indirect OR), not additive as in the linear case.
📖 References
- Robins, J. M., & Greenland, S. (1992). Identifiability and exchangeability for direct and indirect effects. Epidemiology, 3(2), 143–155. doi:10.1097/00001648-199203000-00013
- Pearl, J. (2001). Direct and indirect effects. Proceedings of the 17th Conference on Uncertainty in Artificial Intelligence (UAI), 411–420.
- Imai, K., Keele, L., & Tingley, D. (2010). A general approach to causal mediation analysis. Psychological Methods, 15(4), 309–334. doi:10.1037/a0020761
- Valeri, L., & VanderWeele, T. J. (2013). Mediation analysis allowing for exposure–mediator interactions and causal interpretation. Psychological Methods, 18(2), 137–150. doi:10.1037/a0031034
- VanderWeele, T. J. (2015). Explanation in Causal Inference: Methods for Mediation and Interaction. New York: Oxford University Press. ISBN 978-0-19-932587-0.
- Tingley, D., Yamamoto, T., Hirose, K., Keele, L., & Imai, K. (2014). mediation: R package for causal mediation analysis. Journal of Statistical Software, 59(5), 1–38. doi:10.18637/jss.v059.i05
- VanderWeele, T. J. (2016). Mediation analysis: a practitioner's guide. Annual Review of Public Health, 37, 17–32. doi:10.1146/annurev-publhealth-032315-021402
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
8.3Ordinal & Nominal Outcomes + Categorical Predictors (PO-OR / RRR, g-formula mediation)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
ผลลัพธ์ทางสุขภาพจำนวนมากเป็น หลายระดับ — จัดอันดับ (ordinal) เช่น ระยะของโรค (เล็กน้อย/ปานกลาง/รุนแรง) หรือ ไม่จัดอันดับ (nominal) เช่น ชนิดของวิธีรักษาที่เลือก. การยุบให้เหลือสองกลุ่มทำให้เสียข้อมูล. DAPH ใช้ ordered logit (proportional-odds) สำหรับ ordinal และ multinomial logit สำหรับ nominal และขยาย causal mediation ให้ครอบคลุมทั้งสองด้วย g-formula — รายงานเป็น cumulative OR (ordinal) หรือ relative-risk ratio รายกลุ่ม (nominal). ตัวแปรต้นที่เป็น categorical จะถูกแปลงเป็น dummy พร้อม joint Wald test สำหรับผลรวมของตัวแปร.
Many health outcomes are multi-level — ordinal (disease stage: mild/moderate/severe) or nominal (which treatment modality was chosen). Collapsing to binary discards information. DAPH uses ordered logit (proportional-odds) for ordinal outcomes and multinomial logit for nominal outcomes, and extends causal mediation to both via the g-formula — reported as a cumulative OR (ordinal) or per-category relative-risk ratio (nominal). A categorical predictor is dummy-coded with a joint Wald test for its overall effect.
2หลักการและสูตรLogic and Formula
ordinal: รายงาน cumulative OR (proportional-odds) ของ NDE/NIE/Total · nominal: รายงาน relative-risk ratio รายกลุ่ม
ordinal: report the cumulative (proportional-odds) OR for NDE/NIE/Total · nominal: report the per-category relative-risk ratio
$$ \mathrm{NDE}^{\text{ord}}_{\mathrm{OR}} = \exp\!\Bigl(\overline{\operatorname{logit}\,p^{\ge c}_{10}} - \overline{\operatorname{logit}\,p^{\ge c}_{00}}\Bigr), \qquad \mathrm{NIE}^{\text{nom}}_{\mathrm{RRR},k} = \frac{p_k(x_1,x_1)/p_{\text{ref}}(x_1,x_1)}{p_k(x_1,x_0)/p_{\text{ref}}(x_1,x_0)} $$- τ_c
- จุดตัด (threshold) ของระดับ c — สมมติ proportional odds (β ร่วมทุกจุดตัด)cut-point for level c — proportional-odds assumes a common β across cut-points
- R
- เมทริกซ์เลือกคอนทราสต์ของ dummy ทั้ง k−1 ตัวcontrast-selection matrix over the k−1 dummies
- p_k(x, x′)
- ความน่าจะเป็นเฉลี่ยของกลุ่ม k ภายใต้ X = x และตัวกลางตาม X = x′population-averaged probability of category k under X = x with the mediator distributed as under X = x′
ทำไมต้องใช้ causal mediation: สัมประสิทธิ์ของ logit/ordered/multinomial อยู่บนสเกล log-odds ที่ ไม่ collapsible จึงคูณกันไม่ได้. g-formula คำนวณจากเวกเตอร์ความน่าจะเป็นรายกลุ่มเชิงโต้แย้งโดยตรง จึงให้ผลถูกต้องบนสเกล ratio (Valeri & VanderWeele 2013; Shi และคณะ 2021 — แพ็กเกจ CMAverse). DAPH ตรวจ NDE/NIE เทียบกับการจำลอง Monte-Carlo อิสระและตรงกัน.
Why causal mediation is required: logit/ordered/multinomial coefficients live on a non-collapsible log-odds scale and cannot be multiplied. The g-formula works directly from the counterfactual category-probability vectors, giving correct effects on the ratio scale (Valeri & VanderWeele 2013; Shi et al. 2021 — the CMAverse package). DAPH validates its NDE/NIE against an independent Monte-Carlo simulation.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(MASS); library(nnet); library(car); library(CMAverse)
# Ordinal outcome — proportional-odds (PO-OR)
polr(factor(Y_ord) ~ X1 + X2 + M, method = "logistic", Hess = TRUE)
# Nominal outcome — multinomial (RRR = exp(coef))
multinom(factor(Y_nom) ~ X1 + X2 + M)
# Categorical predictor — overall (joint Wald) effect
Anova(lm(Y ~ factor(region) + age), type = "III")
# Categorical-outcome causal mediation via the g-formula
cmest(data = df, model = "gformula", outcome = "Y_ord", yreg = "ordinal",
exposure = "X1", mediator = "M", basec = c("X2"),
mreg = list("linear"), astar = 0, a = 1)
| Quantity | R | DAPH — measured Δ | Status |
|---|---|---|---|
| Proportional-odds slopes b / SE / p | MASS::polr | Δ ≤ 1.7×10⁻⁵ | ✓ PASS |
| Cut-points (thresholds) | polr zeta | Δ ≤ 9.3×10⁻⁶ | ✓ PASS |
| Multinomial b / SE / p (ทุก contrast) | nnet::multinom | Δ ≤ 4.3×10⁻⁸ | ✓ PASS |
| NDE / NIE / Total — ordinal (cumulative OR) | independent R g-formula | Δ ≤ 2.5×10⁻⁵ | ✓ PASS |
| NDE / NIE / Total — nominal (RRR per category) | independent R g-formula | Δ ≤ 3.0×10⁻⁶ | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 (MASS, nnet) ข้อมูลเดียวกับตาราง 8.2 (N = 800) — ทดสอบครบ 46 รายการ ผ่านทั้งหมด; ผลต่างของ polr/multinom เกิดจาก optimizer (BFGS vs optim) เท่านั้นR 4.3.3 (MASS, nnet), same data as 8.2 (N = 800) — all 46 checks passed; polr/multinom deltas stem from optimizer differences (BFGS vs optim) only.
4การแปลผลและตัวอย่างInterpretation and Example
ordinal: cumulative OR > 1 = แนวโน้มอยู่ในระดับสูงขึ้นของผลลัพธ์ (สมมติ proportional odds — DAPH สรุปเป็น OR เดียวที่เฉลี่ยข้ามจุดตัด) · nominal: RRR แต่ละกลุ่มเทียบกลุ่มอ้างอิง (รหัสต่ำสุด) — NDE/NIE/Total รายงานแยกต่อกลุ่มในตาราง · categorical predictor: ดูค่า joint Wald (ภาพรวมของตัวแปร) ควบคู่กับคอนทราสต์รายระดับ. เช่นเดียวกับ binary การตีความเชิงสาเหตุต้องไม่มีตัวแปรกวนที่ไม่ได้วัด.
Ordinal: a cumulative OR > 1 means a tendency toward higher outcome levels (proportional-odds assumed — DAPH summarises one OR averaged across cut-points) · Nominal: each RRR is relative to the reference category (lowest code) — NDE/NIE/Total are reported per category in the table · Categorical predictor: read the joint Wald (overall variable effect) alongside the level-specific contrasts. As in the binary case, a causal reading requires no unmeasured confounding.
📖 References
- McCullagh, P. (1980). Regression models for ordinal data. Journal of the Royal Statistical Society: Series B, 42(2), 109–142. doi:10.1111/j.2517-6161.1980.tb01109.x
- Agresti, A. (2013). Categorical Data Analysis (3rd ed.). Hoboken: Wiley. ISBN 978-0-470-46363-5.
- VanderWeele, T. J., Vansteelandt, S., & Robins, J. M. (2014). Effect decomposition in the presence of an exposure-induced mediator-outcome confounder. Epidemiology, 25(2), 300–306. doi:10.1097/EDE.0000000000000034
- Vansteelandt, S., & Daniel, R. M. (2017). Interventional effects for mediation analysis with multiple mediators. Epidemiology, 28(2), 258–265. doi:10.1097/EDE.0000000000000596
- Shi, B., Choirat, C., Coull, B. A., VanderWeele, T. J., & Valeri, L. (2021). CMAverse: a suite of functions for reproducible causal mediation analyses. Epidemiology, 32(5), e20–e22. doi:10.1097/EDE.0000000000001378
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 9 — การวิเคราะห์องค์ประกอบ (Factor Analysis: EFA / CFA)Chapter 9 — Factor Analysis (EFA / CFA) ✓ Verified
การวิเคราะห์องค์ประกอบ (Factor Analysis) ลดชุดตัวชี้วัดที่สังเกตได้จำนวนมากให้เหลือ ตัวแปรแฝง (factor / construct) ไม่กี่ตัวที่อธิบายความสัมพันธ์ระหว่างข้อ — เป็นหัวใจของการพัฒนาและตรวจสอบเครื่องมือวัด (แบบสอบถาม / มาตรวัด) ในงานสาธารณสุข. DAPH รองรับสองโหมด — EFA (สำรวจโครงสร้างเมื่อยังไม่มีทฤษฎีชัดเจน) และ CFA (ยืนยันโครงสร้างที่ตั้งสมมติฐานไว้ พร้อมดัชนีความกลมกลืน การประเมินความเชื่อมั่น (Cronbach's α / McDonald's ω) และความตรงเชิงลู่เข้า/เชิงจำแนก (CR/AVE, Fornell–Larcker, HTMT)). รองรับตัวชี้วัดต่อเนื่อง (Pearson) และอันดับ/ทวิภาค (polychoric/tetrachoric). Factor analysis reduces many observed indicators to a few latent variables (factors / constructs) that explain the correlations among the items — the backbone of developing and validating measurement instruments (questionnaires / scales) in public-health research. DAPH supports two modes — EFA (exploring structure when theory is not yet firm) and CFA (confirming a hypothesized structure, with fit indices, reliability (Cronbach's α / McDonald's ω) and convergent/discriminant validity (CR/AVE, Fornell–Larcker, HTMT)). Both handle continuous (Pearson) and ordinal/binary (polychoric/tetrachoric) indicators.
9.1Exploratory Factor Analysis (EFA) — KMO / Bartlett, loadings, communalities, parallel analysis, α / ω
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
EFA ใช้เมื่อยังไม่ทราบว่าตัวชี้วัดจับกลุ่มเป็นองค์ประกอบใด — เช่น พัฒนาแบบวัด "ความรอบรู้ด้านสุขภาพ" ชุดใหม่ 20 ข้อ แล้วต้องการทราบว่าข้อเหล่านั้นสะท้อนกี่มิติ และข้อใดโหลดกับมิติใด. เป็นขั้นแรกของการสร้างมาตรวัดก่อนนำโครงสร้างไปยืนยันด้วย CFA ในกลุ่มตัวอย่างอิสระ.
EFA is used when it is not yet known how indicators cluster into factors — e.g. developing a new 20-item "health literacy" scale and asking how many dimensions the items reflect and which item loads on which dimension. It is the first step of scale construction, before the structure is confirmed with CFA in an independent sample.
2หลักการและสูตรLogic and Formula
- Λ, Φ, Ψ
- เมทริกซ์ค่าน้ำหนัก / สหสัมพันธ์ระหว่างองค์ประกอบ / ความแปรปรวนเฉพาะ (uniqueness)loading matrix / interfactor correlations / unique (residual) variances
- r_ij, p_ij
- สหสัมพันธ์ / สหสัมพันธ์บางส่วน (partial) ของข้อ i กับ jzero-order / partial correlation of items i and j
- h²_i, ψ_i
- ความแปรปรวนที่องค์ประกอบร่วมอธิบาย / ที่เหลือเฉพาะข้อvariance of item i explained by the common factors / left unique
- λ_j^obs
- ค่า eigenvalue ที่สังเกตได้ เทียบกับเปอร์เซ็นไทล์ที่ 95 ของข้อมูลสุ่มobserved eigenvalue vs the 95th percentile from random data
กลไก: DAPH สกัดองค์ประกอบด้วย MINRES/ML/Principal-axis บนเมทริกซ์สหสัมพันธ์ (Pearson หรือ polychoric สำหรับข้อมูลอันดับ) แล้วหมุนแกน — เฉียง (promax/oblimin) เมื่อคาดว่าองค์ประกอบสัมพันธ์กัน หรือ ตั้งฉาก (varimax) เมื่อคาดว่าเป็นอิสระ. จำนวนองค์ประกอบเลือกด้วย parallel analysis (Horn) เป็นค่าเริ่มต้น ซึ่งแม่นกว่าเกณฑ์ Kaiser eigenvalue > 1. ω คำนวณจากค่าน้ำหนักและ uniqueness จึงไม่ต้องอาศัยข้อสมมติ tau-equivalence เหมือน α.
How it works: DAPH extracts factors by MINRES/ML/principal-axis on the correlation matrix (Pearson, or polychoric for ordinal data) and rotates them — obliquely (promax/oblimin) when the factors are expected to correlate, or orthogonally (varimax) when they are expected to be independent. The number of factors defaults to parallel analysis (Horn), which is more accurate than the Kaiser eigenvalue > 1 rule. ω is computed from the loadings and uniquenesses, so unlike α it does not assume tau-equivalence.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(psych)
KMO(df) # sampling adequacy (overall + per item)
cortest.bartlett(cor(df), n = nrow(df)) # sphericity test
fa.parallel(df, fa = "fa", fm = "minres") # parallel analysis -> # factors
efa <- fa(df, nfactors = 3, rotate = "promax", fm = "minres")
print(efa$loadings, cutoff = 0) # pattern matrix (all loadings shown)
efa$communality # communalities h2
omega(df, nfactors = 3)$omega.tot # McDonald's omega
alpha(df[, items_F1])$total$raw_alpha # Cronbach's alpha (per factor)
| Quantity | R (psych 2.4.1) | DAPH — measured Δ | Status |
|---|---|---|---|
| KMO (overall + per-item MSA) | KMO() | Δ ≤ 5.0×10⁻⁴ | ✓ PASS |
| Bartlett χ² / df / p | cortest.bartlett() | Δ ≤ 4.3×10⁻⁴ / exact / same | ✓ PASS |
| Parallel-analysis # factors (Horn q95) | fa.parallel() | 3 = 3 (identical) | ✓ PASS |
| Pattern loadings (minres+promax · ml+varimax) | fa() | Δ ≤ 5.4×10⁻⁵ | ✓ PASS |
| Communalities h² + factor corr Φ | $communality / $Phi | Δ ≤ 5.2×10⁻⁵ / 3.7×10⁻⁴ | ✓ PASS |
| Polychoric path (ordinal): loadings / eigen / KMO | fa(cor="poly") | Δ ≤ 5.1×10⁻⁵ | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 (psych 2.4.1, GPArotation) ข้อมูลจำลอง N = 500, 9 ตัวชี้วัด 3 องค์ประกอบ (Pearson + polychoric) — 27 รายการตรวจ; การทดสอบรอบนี้พบและแก้บั๊กการเรียงลำดับ Φ ของไลบรารี factor_analyzer ในกรณี oblique rotation แล้ว (ผล Φ/h² ตรง psych ทุกกรณีหลังแก้)R 4.3.3 (psych 2.4.1, GPArotation), simulated N = 500, 9 indicators / 3 factors (Pearson + polychoric) — 27 checks; this run uncovered and fixed a factor-order bug in factor_analyzer's Φ under oblique rotation (Φ/h² now match psych in every case).
4การแปลผลและตัวอย่างInterpretation and Example
ความเพียงพอของข้อมูล: KMO ≥ .60 ยอมรับได้, ≥ .80 ดีมาก (Kaiser 1974); Bartlett ต้องมีนัยสำคัญ (p < .05). ค่าน้ำหนัก: ถือว่าเด่นเมื่อ |λ| ≥ .32 (≈ ความแปรปรวนร่วม 10%) และควรใช้เกณฑ์สูงขึ้นเมื่อ N น้อย; ข้อที่โหลดเด่นในหลายองค์ประกอบ (cross-loading, ผลต่าง < .20) ควรพิจารณาตัด. communality ≥ .40 แสดงว่าองค์ประกอบอธิบายข้อได้พอ. จำนวนองค์ประกอบ: ยึด parallel analysis เป็นหลัก. ความเชื่อมั่น: α และ ω ≥ .70 ยอมรับได้ (ω นิยมมากกว่าเพราะไม่อิง tau-equivalence — Hayes & Coutts 2020). โครงสร้างที่ได้เป็นผลเชิงสำรวจ ควรยืนยันด้วย CFA.
Sampling adequacy: KMO ≥ .60 acceptable, ≥ .80 meritorious (Kaiser 1974); Bartlett must be significant (p < .05). Loadings: salient when |λ| ≥ .32 (≈ 10% shared variance), with higher cut-offs at smaller N; items loading saliently on several factors (cross-loading, difference < .20) should be considered for removal. Communality ≥ .40 shows a factor captures the item adequately. Number of factors: rely on parallel analysis. Reliability: α and ω ≥ .70 are acceptable (ω is preferred, being free of the tau-equivalence assumption — Hayes & Coutts 2020). The structure is exploratory and should be confirmed with CFA.
📖 References
- Fabrigar, L. R., Wegener, D. T., MacCallum, R. C., & Strahan, E. J. (1999). Evaluating the use of exploratory factor analysis in psychological research. Psychological Methods, 4(3), 272–299. doi:10.1037/1082-989X.4.3.272
- Costello, A. B., & Osborne, J. W. (2005). Best practices in exploratory factor analysis: four recommendations for getting the most from your analysis. Practical Assessment, Research & Evaluation, 10(7), 1–9.
- Watkins, M. W. (2018). Exploratory factor analysis: A guide to best practice. Journal of Black Psychology, 44(3), 219–246. doi:10.1177/0095798418771807
- Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30(2), 179–185. doi:10.1007/BF02289447
- Kaiser, H. F. (1974). An index of factorial simplicity. Psychometrika, 39(1), 31–36. doi:10.1007/BF02291575
- Bartlett, M. S. (1950). Tests of significance in factor analysis. British Journal of Statistical Psychology, 3(2), 77–85. doi:10.1111/j.2044-8317.1950.tb00285.x
- Hayes, A. F., & Coutts, J. J. (2020). Use omega rather than Cronbach's alpha for estimating reliability. But… Communication Methods and Measures, 14(1), 1–24. doi:10.1080/19312458.2020.1718629
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
9.2Confirmatory Factor Analysis (CFA) — fit indices, CR / AVE, Fornell–Larcker, HTMT
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
CFA ทดสอบ โครงสร้างการวัดที่กำหนดไว้ล่วงหน้า — ผู้วิจัยระบุว่าข้อใดวัดองค์ประกอบใด แล้วประเมินว่าข้อมูลกลมกลืนกับโมเดลนั้นเพียงใด. เป็นมาตรฐานสำหรับการยืนยันความตรงของโครงสร้าง (construct validity) ของแบบวัดก่อนนำไปใช้ในการวิเคราะห์เชิงโครงสร้าง (SEM) หรือรายงานผลในวารสาร.
CFA tests a pre-specified measurement structure — the researcher states which items measure which factor, then evaluates how well the data fit that model. It is the standard for confirming the construct validity of a scale before it is used in structural (SEM) analyses or reported in journals.
2หลักการและสูตรLogic and Formula
- Λ, Φ, Θ_δ
- ค่าน้ำหนัก / สหสัมพันธ์ระหว่างองค์ประกอบแฝง / ความแปรปรวน-ร่วมของส่วนคลาดเคลื่อนของข้อloadings / latent-factor correlations / indicator error covariance
- λ_i, φ_ij
- ค่าน้ำหนักมาตรฐานของข้อ i / สหสัมพันธ์ระหว่างองค์ประกอบ i กับ jstandardized loading of item i / correlation between factors i and j
- AVE, CR
- ความแปรปรวนเฉลี่ยที่สกัดได้ / ความเชื่อมั่นรวม (เทียบเท่า McDonald's ω)average variance extracted / composite reliability (= McDonald's ω)
- HTMT
- อัตราส่วน heterotrait–monotrait ของสหสัมพันธ์ระหว่างข้อheterotrait–monotrait ratio of item correlations
กลไก: DAPH ประมาณค่าด้วย ML (ต่อเนื่อง) หรือ ULS บนสหสัมพันธ์ polychoric/tetrachoric (อันดับ/ทวิภาค) โดยตรึงค่าน้ำหนักของตัวชี้วัดตัวแรกในแต่ละองค์ประกอบไว้ที่ 1.0 เพื่อกำหนดสเกล. คำนวณดัชนีความกลมกลืนจากเมทริกซ์ความแปรปรวนร่วมที่โมเดลบ่งชี้ (Σ̂) เทียบกับที่สังเกต (S); CR/AVE จากค่าน้ำหนักมาตรฐาน; HTMT จากสหสัมพันธ์ที่สังเกตจริง — และตรวจ Heywood case (ค่าน้ำหนักมาตรฐาน > 1 หรือความแปรปรวนคงเหลือติดลบ) อัตโนมัติ.
How it works: DAPH estimates by ML (continuous) or ULS on the polychoric/tetrachoric correlations (ordinal/binary), fixing the first indicator of each factor to 1.0 to set the scale. Fit indices come from the model-implied covariance (Σ̂) versus the observed (S); CR/AVE from the standardized loadings; HTMT from the observed item correlations — and it automatically flags Heywood cases (standardized loading > 1 or negative residual variance).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(lavaan); library(semTools)
model <- '
F1 =~ x1 + x2 + x3
F2 =~ x4 + x5 + x6
F3 =~ x7 + x8 + x9
'
fit <- cfa(model, data = df, estimator = "ML") # ordered = c(...) for ordinal
summary(fit, fit.measures = TRUE, standardized = TRUE) # loadings + chi2/CFI/TLI/RMSEA/SRMR
compRelSEM(fit) # composite reliability (= McDonald's omega)
AVE(fit) # average variance extracted
htmt(model, data = df) # heterotrait-monotrait ratio (discriminant validity)
| Quantity | R (lavaan 0.6.21 / semTools 0.5.8) | DAPH — measured Δ | Status |
|---|---|---|---|
| Standardized loadings (9 items) | standardizedSolution() | Δ ≤ 1.3×10⁻⁴ | ✓ PASS |
| χ² / df / p / CFI / TLI / RMSEA(CI) / SRMR | fitMeasures() | Δ ≤ 2.4×10⁻⁴ (χ²) · ≤ 5×10⁻⁵ (ดัชนี) | ✓ PASS |
| logLik / AIC / BIC | fitMeasures() | 11632.554 = 11632.554 (exact) | ✓ PASS |
| CR (= ω) / AVE / Cronbach's α | compRelSEM · AVE · alpha() | Δ ≤ 3.9×10⁻⁴ | ✓ PASS |
| HTMT + Fornell–Larcker √AVE | semTools::htmt() | Δ ≤ 5.0×10⁻⁴ | ✓ PASS |
| Error covariance (respecification): est / Δχ² / std | x1 ~~ x2 freed | Δ ≤ 9×10⁻⁶ / 6×10⁻⁴ / 0.119 = 0.1186 | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 ข้อมูลจำลอง N = 500, 3 องค์ประกอบ × 3 ตัวชี้วัด, ทั้งโมเดลฐานและโมเดล respecified — 25 รายการตรวจ; AIC/BIC ปรับเป็นสเกล log-likelihood จริง (ตรง lavaan เป๊ะ) และ standardized error covariance ใช้นิยาม residual correlation ตาม lavaan/AMOS แล้วR 4.3.3, simulated N = 500, 3 factors × 3 indicators, base + respecified models — 25 checks; AIC/BIC now on the true log-likelihood scale (exactly matching lavaan) and standardized error covariances use the lavaan/AMOS residual-correlation convention.
4การแปลผลและตัวอย่างInterpretation and Example
ความกลมกลืน (Hu & Bentler 1999): เหมาะสมดี CFI/TLI ≥ .95, RMSEA ≤ .06, SRMR ≤ .05; ยอมรับได้ CFI/TLI ≥ .90, RMSEA ≤ .08, SRMR ≤ .08. ความตรงเชิงลู่เข้า: ค่าน้ำหนักมาตรฐานมีนัยสำคัญและควร ≥ .50; CR ≥ .70 และ AVE ≥ .50. ความตรงเชิงจำแนก: Fornell–Larcker กำหนดให้ √AVE ของแต่ละองค์ประกอบมากกว่าสหสัมพันธ์ระหว่างองค์ประกอบ; HTMT < .85 (เข้ม) หรือ < .90 (หลวม) — HTMT ตรวจจับการละเมิดได้ไวกว่า Fornell–Larcker (Henseler 2015). Heywood case (β > 1 หรือความแปรปรวนคงเหลือติดลบ) บ่งชี้โมเดลไม่เสถียร/ระบุไม่ได้ ควรทบทวน. ผลควรตีความภายใต้โครงสร้างที่กำหนดไว้ล่วงหน้าและลักษณะกลุ่มตัวอย่าง.
Fit (Hu & Bentler 1999): good CFI/TLI ≥ .95, RMSEA ≤ .06, SRMR ≤ .05; acceptable CFI/TLI ≥ .90, RMSEA ≤ .08, SRMR ≤ .08. Convergent validity: standardized loadings significant and preferably ≥ .50; CR ≥ .70 and AVE ≥ .50. Discriminant validity: Fornell–Larcker requires each factor's √AVE to exceed its interfactor correlations; HTMT < .85 (strict) or < .90 (liberal) — HTMT detects violations more sensitively than Fornell–Larcker (Henseler 2015). A Heywood case (β > 1 or negative residual variance) signals an unstable/under-identified model that should be revisited. Interpret results in light of the a priori structure and the sample.
📖 References
- Brown, T. A. (2015). Confirmatory Factor Analysis for Applied Research (2nd ed.). New York: Guilford Press. ISBN 978-1-4625-1779-4.
- Hu, L., & Bentler, P. M. (1999). Cutoff criteria for fit indexes in covariance structure analysis. Structural Equation Modeling, 6(1), 1–55. doi:10.1080/10705519909540118
- Fornell, C., & Larcker, D. F. (1981). Evaluating structural equation models with unobservable variables and measurement error. Journal of Marketing Research, 18(1), 39–50. doi:10.1177/002224378101800104
- Henseler, J., Ringle, C. M., & Sarstedt, M. (2015). A new criterion for assessing discriminant validity in variance-based structural equation modeling. Journal of the Academy of Marketing Science, 43(1), 115–135. doi:10.1007/s11747-014-0403-8
- Schreiber, J. B., Nora, A., Stage, F. K., Barlow, E. A., & King, J. (2006). Reporting structural equation modeling and confirmatory factor analysis results: A review. The Journal of Educational Research, 99(6), 323–338. doi:10.3200/JOER.99.6.323-338
- Kline, R. B. (2016). Principles and Practice of Structural Equation Modeling (4th ed.). New York: Guilford Press. ISBN 978-1-4625-2334-4.
- Rosseel, Y. (2012). lavaan: an R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36. doi:10.18637/jss.v048.i02
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 10 — โมเดลสมการโครงสร้าง (SEM & GSEM — ตัวแปรแฝง)Chapter 10 — Structural Equation Modeling (SEM & GSEM — latent variables) ✓ Verified
โมเดลสมการโครงสร้าง (SEM) ต่อยอดจากการวิเคราะห์เส้นทางโดยเพิ่ม โมเดลการวัด (CFA) — สร้าง ตัวแปรแฝง (latent constructs) จากตัวชี้วัดหลายตัว แล้วประมาณ โมเดลการวัด + โมเดลเชิงโครงสร้าง พร้อมกัน. ต่างจากบทที่ 8 (Path Analysis ใช้ตัวแปรสังเกตได้ล้วน) — SEM แยกความคลาดเคลื่อนของการวัดออกจากความสัมพันธ์เชิงโครงสร้าง จึงลดอคติจาก measurement error. GSEM ขยาย SEM ให้รองรับ ตัวแปรตามแบบ categorical (binary/ordinal/nominal) ผ่าน link function. ทั้งสองเป็นมาตรฐานทองของงานวิจัยเชิงทฤษฎีด้านสาธารณสุขที่มีตัวแปรวัดไม่ได้โดยตรง (เช่น คุณภาพชีวิต ความรอบรู้สุขภาพ พฤติกรรมเสี่ยง). Structural equation modeling (SEM) extends path analysis by adding a measurement model (CFA) — it builds latent constructs from multiple indicators and estimates the measurement and structural models jointly. Unlike Chapter 8 (path analysis on observed variables only), SEM separates measurement error from the structural relations, reducing attenuation bias. GSEM generalizes SEM to categorical outcomes (binary/ordinal/nominal) via a link function. Both are the gold standard for theory-driven public-health research involving constructs that cannot be measured directly (quality of life, health literacy, risk behaviour).
10.1Structural Equation Modeling — CFA measurement + structural model (loadings, CR/AVE, discriminant validity, direct/indirect/total, model fit)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
SEM ตอบคำถามที่ regression และ path analysis แบบสังเกตได้ตอบไม่ได้ — เมื่อตัวแปรสำคัญ (เช่น "พฤติกรรมเสี่ยง" หรือ "การสนับสนุนทางสังคม") วัดตรงไม่ได้ แต่สะท้อนผ่านตัวชี้วัดหลายตัว. SEM สร้างตัวแปรแฝงจากตัวชี้วัดเหล่านั้น (โมเดลการวัด CFA) แล้วประเมินเส้นทางเชิงโครงสร้างระหว่างองค์ประกอบแฝง — โดย ล้างความคลาดเคลื่อนของการวัด ออกก่อน. ผลคือค่าสัมประสิทธิ์ที่ไม่ถูกลดทอน (unattenuated) และการทดสอบความกลมกลืนของทั้งทฤษฎี.
SEM answers what observed-variable regression and path analysis cannot — when a key variable (e.g. "risk behaviour" or "social support") cannot be measured directly but is reflected by several indicators. SEM builds latent constructs from those indicators (the CFA measurement model) and then estimates structural paths among the constructs after removing measurement error. The result is unattenuated coefficients and a global test of the entire theory.
2หลักการและสูตรLogic and Formula
- λ_i, ξ, η
- ค่าน้ำหนักองค์ประกอบ / ตัวแปรแฝงต้นทาง (exogenous) / ตัวแปรแฝงปลายทาง (endogenous)factor loading / exogenous latent / endogenous latent
- B, Γ
- เมทริกซ์เส้นทางระหว่างแฝงปลายทาง / จากแฝงต้นทางสู่ปลายทางlatent→latent path matrix / exogenous→endogenous paths
- CR, AVE
- ความเชื่อมั่นรวม (= McDonald's ω) / ความแปรปรวนเฉลี่ยที่สกัดได้composite reliability (= McDonald's ω) / average variance extracted
- HTMT
- อัตราส่วน heterotrait–monotrait สำหรับความตรงเชิงจำแนกheterotrait–monotrait ratio for discriminant validity
กลไก: DAPH ประมาณโมเดลการวัด (=~) และโมเดลเชิงโครงสร้าง (~) พร้อมกัน ด้วย ML (semopy) — ให้ค่าน้ำหนักมาตรฐาน, CR/AVE/α, Fornell–Larcker, HTMT, ดัชนีกลมกลืนครบชุด (χ²/df, CFI, TLI, RMSEA[CI], SRMR, GFI, AGFI, NFI), และแจกแจงอิทธิพลทางตรง/อ้อม/รวมพร้อม Monte-Carlo CI (Preacher & Selig 2012). แผนภาพวาดตามหลักมาตรฐาน (วงรี = แฝง, สี่เหลี่ยม = ตัวชี้วัด, ลูกศรเดี่ยว → = ทิศทาง, สองหัวโค้ง ↔ = สหสัมพันธ์, disturbance บนตัวแปรตาม).
How it works: DAPH estimates the measurement (=~) and structural (~) models jointly by ML (semopy) — returning standardized loadings, CR/AVE/α, Fornell–Larcker, HTMT, the full fit-index set (χ²/df, CFI, TLI, RMSEA[CI], SRMR, GFI, AGFI, NFI), and a direct/indirect/total decomposition with Monte-Carlo CIs (Preacher & Selig, 2012). The diagram follows standard conventions (ellipse = latent, rectangle = indicator, single arrow → = directed, curved double arrow ↔ = covariance, a disturbance on each endogenous construct).
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(lavaan)
model <- '
# measurement model (CFA)
SocSup =~ s1 + s2 + s3 + s4
PhysAct =~ p1 + p2 + p3
QoL =~ q1 + q2 + q3 + q4
# structural model
PhysAct ~ a*SocSup
QoL ~ b*PhysAct + cp*SocSup
ind := a*b # indirect SocSup -> PhysAct -> QoL
tot := cp + a*b # total effect
'
fit <- sem(model, data = df, estimator = "ML")
summary(fit, fit.measures = TRUE, standardized = TRUE)
# CR/AVE via semTools::reliability(fit) ; HTMT via semTools::htmt(model, df)
| Quantity | R (lavaan 0.6.21 / semTools 0.5.8) | DAPH — measured Δ | Status |
|---|---|---|---|
| Standardized loadings λ (7) + structural β (4) | standardizedSolution() | Δ ≤ 1.7×10⁻⁴ | ✓ PASS |
| χ² / df / p | 30.016 / 25 / 0.2237 | 30.017 / 25 / 0.2237 | ✓ PASS |
| CFI / TLI / RMSEA / SRMR | fitMeasures() | Δ ≤ 5×10⁻⁴ · RMSEA 0.0169 = 0.0169 | ✓ PASS |
| logLik / AIC / BIC | −9688.992 / 19417.984 / 19509.005 | identical (exact) | ✓ PASS |
| Indirect (MC CI) + Total (std) | := a*b + monteCarloCI | Δ ≤ 4.4×10⁻⁵; CI overlap ✓ | ✓ PASS |
| CR / AVE / α / HTMT / Fornell–Larcker | semTools | Δ ≤ 4×10⁻⁴ (HTMT ≤ 2×10⁻³) | ✓ PASS |
| Descriptives + correlation table | cor() on composites | Δ ≤ 5×10⁻⁴ | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 ข้อมูลจำลอง N = 700 (2 องค์ประกอบแฝง + ตัวแปรสังเกต 2 ตัว + การส่งผ่าน) — 35 รายการตรวจ; df/χ²p/AIC/BIC ใช้ convention เดียวกับ lavaan (fixed.x = FALSE) หลังการแก้ในรอบนี้ · ข้อจำกัดที่เปิดเผย: SE ของ β มาตรฐานใช้การสเกลอย่างง่าย ให้ CI กว้างกว่า lavaan delta-method ได้ถึง ~18% (อนุรักษ์นิยม; ค่าประมาณและข้อสรุปนัยสำคัญตรงกัน) และ GFI/AGFI ของ DAPH ใช้นิยามต่างจาก lavaan เล็กน้อยR 4.3.3, simulated N = 700 (2 latents + 2 observed + mediation) — 35 checks; df/χ² p/AIC/BIC follow the lavaan convention (fixed.x = FALSE) after this round's fix. Disclosed limitations: standardized-β SEs use a simple rescaling giving CIs up to ~18% wider than lavaan's delta method (conservative; estimates and significance conclusions agree), and DAPH's GFI/AGFI definitions differ slightly from lavaan's.
4การแปลผลและตัวอย่างInterpretation and Example
โมเดลการวัด: ค่าน้ำหนักมาตรฐาน ≥ 0.50 (ดี ≥ 0.70) · CR ≥ 0.70 และ AVE ≥ 0.50 = ความตรงเชิงลู่เข้า · √AVE > สหสัมพันธ์ระหว่างองค์ประกอบ (Fornell–Larcker) และ HTMT < 0.85 = ความตรงเชิงจำแนก. ความกลมกลืน (Hu & Bentler 1999): CFI/TLI ≥ 0.95, RMSEA ≤ 0.06, SRMR ≤ 0.08 (ดีเยี่ยม). การส่งผ่าน: ตัดสินจาก Monte-Carlo CI ของอิทธิพลทางอ้อม (ไม่คร่อม 0 = นัยสำคัญ). ⚠ ถ้าค่าน้ำหนักติดลบ/ต่ำมาก หรือ CR/AVE ต่ำกว่าเกณฑ์ = ตัวชี้วัดไม่รวมเป็นองค์ประกอบเดียวกัน ควรทบทวน (reverse-code หรือ ตัดข้อ).
Measurement model: standardized loadings ≥ 0.50 (good ≥ 0.70); CR ≥ 0.70 and AVE ≥ 0.50 = convergent validity; √AVE > interfactor correlations (Fornell–Larcker) and HTMT < 0.85 = discriminant validity. Fit (Hu & Bentler 1999): CFI/TLI ≥ 0.95, RMSEA ≤ 0.06, SRMR ≤ 0.08 (excellent). Mediation: judge from the indirect effect's Monte-Carlo CI (significant if it excludes 0). ⚠ Negative/very low loadings or below-threshold CR/AVE mean the items do not form a coherent construct — reconsider (reverse-code or drop items).
📖 References
- Bollen, K. A. (1989). Structural Equations with Latent Variables. New York: Wiley. ISBN 978-0-471-01171-2.
- Kline, R. B. (2016). Principles and Practice of Structural Equation Modeling (4th ed.). New York: Guilford Press. ISBN 978-1-4625-2334-4.
- Hu, L., & Bentler, P. M. (1999). Cutoff criteria for fit indexes in covariance structure analysis. Structural Equation Modeling, 6(1), 1–55. doi:10.1080/10705519909540118
- Fornell, C., & Larcker, D. F. (1981). Evaluating structural equation models with unobservable variables and measurement error. Journal of Marketing Research, 18(1), 39–50. doi:10.1177/002224378101800104
- Henseler, J., Ringle, C. M., & Sarstedt, M. (2015). A new criterion for assessing discriminant validity in variance-based structural equation modeling. Journal of the Academy of Marketing Science, 43(1), 115–135. doi:10.1007/s11747-014-0403-8
- Preacher, K. J., & Selig, J. P. (2012). Advantages of Monte Carlo confidence intervals for indirect effects. Communication Methods and Measures, 6(2), 77–98. doi:10.1080/19312458.2012.679848
- Rosseel, Y. (2012). lavaan: an R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36. doi:10.18637/jss.v048.i02
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
10.2Generalized SEM — categorical outcome (logit / ordered / multinomial; OR / RRR; g-formula mediation)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
GSEM คือ SEM ที่ตัวแปรตามเป็น categorical — สอง/หลายกลุ่ม หรือจัดอันดับ (เช่น เป็นโรค/ไม่เป็น, ระดับคุณภาพชีวิต ต่ำ/กลาง/สูง). ผลลัพธ์ทางสุขภาพจำนวนมากเป็นแบบนี้ ไม่ใช่ค่าต่อเนื่อง. GSEM ประมาณ โมเดลการวัด (CFA) ให้คะแนนองค์ประกอบ แล้วป้อนเข้าโมเดล logit/ordered-logit/multinomial-logit — รายงานอิทธิพลเป็น Odds Ratio (OR) หรือ Relative-Risk Ratio (RRR). อิทธิพลทางอ้อมใช้ g-formula (counterfactual) เพราะบนสเกล OR ใช้ผลคูณสัมประสิทธิ์ไม่ได้ (non-collapsibility). การแบ่งหน้าที่ (กติกา DAPH): GSEM รับตัวแปรตามเชิงกลุ่มเท่านั้น — ตัวแปรตามต่อเนื่องใช้ SEM (หัวข้อ 10.1) · ส่วนตัวแปรส่งผ่านเป็นได้ทุกประเภททั้งสองสถิติ — ตัวกลางแบบกลุ่มถูกแยก dummy อัตโนมัติ (ใน GSEM สมการเป็น logit แท้; ใน SEM เป็น linear-probability) ไม่ปฏิบัติเป็นคะแนนต่อเนื่อง.
GSEM is SEM with a categorical outcome — binary, nominal, or ordinal (e.g. disease yes/no, QoL low/medium/high). Many health outcomes are of this kind rather than continuous. GSEM estimates a CFA measurement model to obtain factor scores and feeds them into a logit / ordered-logit / multinomial-logit structural model — reporting effects as Odds Ratios (OR) or Relative-Risk Ratios (RRR). Indirect effects use the counterfactual g-formula because products-of-coefficients are invalid on the odds scale (non-collapsibility). Division of labour (DAPH rule): GSEM takes a categorical outcome only; a continuous outcome belongs to SEM (topic 10.1). Mediators may be of any type in both — categorical mediators are dummy-expanded (TRUE logit equations here; linear-probability in SEM), never scored as continuous codes.
2หลักการและสูตรLogic and Formula
- g(·), β
- link function (logit) / สัมประสิทธิ์ log-odds (exp → OR/RRR)link function (logit) / log-odds coefficient (exp → OR/RRR)
- NDE, NIE
- อิทธิพลทางตรง/ทางอ้อมตามธรรมชาติ (counterfactual)natural direct / indirect effect (counterfactual)
- ℓ, k, N
- log-likelihood / จำนวนพารามิเตอร์ / ขนาดตัวอย่างlog-likelihood / # parameters / sample size
กลไก: DAPH ใช้ CFA (semopy) → คะแนนองค์ประกอบมาตรฐาน → statsmodels Logit/OrderedModel/MNLogit. อิทธิพลทางอ้อมใช้ g-formula (Valeri & VanderWeele 2013; VanderWeele 2015) — Direct(NDE)/Indirect(NIE)/Total ทั้งหมดจาก g-formula ทำให้ Direct × Indirect ≈ Total บนสเกลอัตราส่วน. factor-score regression เป็นวิธีที่ยอมรับได้ (Croon 2002; Devlieger et al. 2016) เมื่อ full-information GSEM ไม่พร้อมใช้.
How it works: DAPH uses CFA (semopy) → standardized factor scores → statsmodels Logit/OrderedModel/MNLogit. Indirect effects use the g-formula (Valeri & VanderWeele, 2013; VanderWeele, 2015) — Direct(NDE)/Indirect(NIE)/Total all come from the g-formula so Direct × Indirect ≈ Total on the ratio scale. Factor-score regression is a recognized approach (Croon, 2002; Devlieger et al., 2016) when full-information GSEM is unavailable.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(lavaan); library(CMAverse)
# stage 1: CFA factor scores
cfa <- cfa('SocSup =~ s1+s2+s3+s4', data = df)
df$SocSup <- lavPredict(cfa)
# stage 2: categorical structural model + g-formula natural effects
res <- cmest(data = df, model = "gformula", outcome = "depression",
exposure = "SocSup", mediator = "bmi",
yreg = "logistic", mreg = list("linear"),
EMint = FALSE, estimation = "imputation", inference = "bootstrap")
summary(res) # Rcde (NDE-OR), Rpnie (NIE-OR), Rte (total-OR), pm
| Quantity | R gold standard | DAPH — measured Δ | Status |
|---|---|---|---|
| ขั้นที่ 1 — CFA loadings / CR / AVE | lavaan::cfa + semTools | Δ ≤ 4.5×10⁻⁵ (CR/AVE ≤ 3.7×10⁻⁴) | ✓ PASS |
| Binary: logit b / SE / p / OR | glm(binomial) บน factor scores เดียวกัน | Δ ≤ 3×10⁻¹³ | ✓ PASS |
| Ordinal: slopes + cut-points | MASS::polr (zeta) | Δ ≤ 5.7×10⁻⁶ / 2.5×10⁻⁴ | ✓ PASS |
| Nominal: RRR + CI + p (ทุก contrast) | nnet::multinom | Δ ≤ 5.6×10⁻⁹ | ✓ PASS |
| NDE / NIE / Total (g-formula ทุก family) | independent R g-formula | binary < 10⁻¹⁰ · ordinal ≤ 8.3×10⁻⁶ · nominal ≤ 1.6×10⁻⁶ | ✓ PASS |
| Binary covariate 1/2, 5/10 → auto 0/1 | glm with recoded var | Δ ≤ 4×10⁻¹² | ✓ PASS |
| logLik / AIC / BIC / McFadden / Nagelkerke | logLik() + hand-computed pseudo-R² | Δ ≤ 5×10⁻⁴ | ✓ PASS |
| χ²/CFI/RMSEA (ไม่นิยามสำหรับ categorical ML) | not defined | suppressed (ถูกต้องตามหลัก generalized SEM) | ✓ PASS |
📐 ทวนสอบจริง 2026-07-04:📐 Verified by actual run 2026-07-04: R 4.3.3 ข้อมูลจำลอง N = 900 (binary/ordinal) + N = 1,500 (nominal) รวม 72 รายการตรวจ; cut-points ปรับให้รายงานเป็นค่า threshold จริง (ตรง R polr zeta) ในรอบนี้ · หมายเหตุความโปร่งใส: DAPH ใช้ two-stage factor-score regression (Croon 2002; Devlieger et al. 2016) — ไม่ใช่ full-information ML; ผล OR จึงอาจต่างจากตัวประมาณแบบ full-information เล็กน้อยตามวิธีคะแนนองค์ประกอบ (ทดสอบ sensitivity ด้วยคะแนนองค์ประกอบสองแบบ ให้ OR ต่างกันน้อยมาก)R 4.3.3, simulated N = 900 (binary/ordinal) + N = 1,500 (nominal), 72 checks total; cut-points now report true thresholds (matching R polr zeta) as of this round. Transparency note: DAPH uses two-stage factor-score regression (Croon 2002; Devlieger et al. 2016) — not full-information ML; ORs can differ slightly from a full-information estimator depending on the factor-score method (sensitivity test with two factor-score methods shifted ORs only marginally).
4การแปลผลและตัวอย่างInterpretation and Example
ค่าอิทธิพล: OR/RRR > 1 = เพิ่มความเสี่ยง/อัตราส่วน, < 1 = ลด (ตัดสินนัยสำคัญจาก 95% CI ที่ไม่คร่อม 1). คุณภาพโมเดล: McFadden R² ≥ 0.2 = เหมาะสมดี; เปรียบเทียบโมเดลด้วย AIC/BIC (ต่ำกว่า = ดีกว่า). ⚠ ห้ามรายงาน χ²/CFI/TLI/RMSEA/SRMR — ไม่นิยามสำหรับตัวแปรตาม categorical ที่ประมาณด้วย ML (หลักการมาตรฐานของ generalized SEM). การส่งผ่าน: โมเดลต้องเป็น DAG (ไม่มีวงจร) จึงจะแจกแจง NDE/NIE ได้; ถ้ามีเส้นสองทิศ ระบบเตือนและแสดงเฉพาะอิทธิพลทางตรง.
Effects: OR/RRR > 1 raises the odds/risk-ratio, < 1 lowers it (significant when the 95% CI excludes 1). Model quality: McFadden R² ≥ 0.2 indicates good fit; compare nested models by AIC/BIC (lower is better). ⚠ Do NOT report χ²/CFI/TLI/RMSEA/SRMR — undefined for a categorical ML outcome (the standard generalized-SEM convention). Mediation: the model must be a DAG (no cycles) to decompose NDE/NIE; bidirectional paths trigger a warning and only direct effects are shown.
📖 References
- Valeri, L., & VanderWeele, T. J. (2013). Mediation analysis allowing for exposure–mediator interactions and causal interpretation. Psychological Methods, 18(2), 137–150. doi:10.1037/a0031034
- VanderWeele, T. J. (2015). Explanation in Causal Inference: Methods for Mediation and Interaction. New York: Oxford University Press. ISBN 978-0-19-932587-0.
- Croon, M. (2002). Using predicted latent scores in general latent structure models. In G. A. Marcoulides & I. Moustaki (Eds.), Latent Variable and Latent Structure Models (pp. 195–223). Mahwah, NJ: Erlbaum. ISBN 978-0-8058-4046-7.
- Devlieger, I., Mayer, A., & Rosseel, Y. (2016). Hypothesis testing using factor score regression. Educational and Psychological Measurement, 76(5), 741–770. doi:10.1177/0013164415607618
- Tzang, R.-F., & Chang, Y.-C. (2022). Generalized structural equation modeling: symptom heterogeneity in ADHD. World Journal of Psychiatry, 12(6), 787–800. doi:10.5498/wjp.v12.i6.787
- Fornell, C., & Larcker, D. F. (1981). Evaluating structural equation models with unobservable variables and measurement error. Journal of Marketing Research, 18(1), 39–50. doi:10.1177/002224378101800104
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 11 — เครื่องมือทั่วไป (Descriptive / Utility)Chapter 11 — Descriptive / Utility ✓ Verified
เครื่องมือสนับสนุนการวิเคราะห์ที่ผู้ใช้ DAPH เรียกใช้ก่อนหรือหลัง main analysis Support tools that DAPH users invoke before or after their main analysis.
11.1Cronbach's α — Reliability Coefficient
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Cronbach's α วัด internal consistency reliability ของแบบสอบถาม/scale — ระดับที่ items ใน scale วัดเรื่องเดียวกัน. ค่าระหว่าง 0–1; ≥0.70 ยอมรับได้, ≥0.80 ดี, ≥0.90 ดีมาก (Nunnally 1978). พัฒนาโดย Lee J. Cronbach (1951).
Cronbach's α measures internal consistency reliability of a scale — how strongly the items measure the same construct. Range 0–1; ≥0.70 acceptable, ≥0.80 good, ≥0.90 excellent (Nunnally 1978). Cronbach (1951).
2หลักการและสูตรLogic and Formula
- k
- จำนวน items ใน scalenumber of scale items
- σ_i²
- variance ของ item ivariance of item i
- σ_T²
- variance ของ total score (ผลรวม items)variance of the total score
α สูงต้องการ inter-item correlation สูงและจำนวน items มาก. รายงาน "α if item deleted" เพื่อระบุ item ที่อาจตัดออกเพื่อเพิ่ม reliability.
High α requires high inter-item correlation and many items. Report "α if item deleted" to identify items whose removal would boost reliability.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(psych); data(bfi)
items <- bfi[, c("A1","A2","A3","A4","A5")]
alpha(items)
# raw_alpha = 0.704
# std.alpha = 0.706
# Per item α if deleted: A1=0.717, A2=0.643, A3=0.625, A4=0.665, A5=0.654
| Quantity | R psych | DAPH | Status |
|---|---|---|---|
| raw α | 0.7040 | 0.7040 | ✓ PASS |
| α (A2 deleted) | 0.6433 | 0.6433 | ✓ PASS |
4การแปลผลและตัวอย่างInterpretation and Example
รายงาน α (raw + standardised) + 95% CI + α-if-item-deleted + average inter-item correlation. ระวัง: α ที่สูงเกิน 0.95 อาจแสดง redundancy (items ซ้ำซ้อน) มากกว่า reliability ที่แท้จริง — ควรพิจารณาตัด item.
Report α (raw + standardised) + 95% CI + α-if-item-deleted + average inter-item correlation. Caveat: α > 0.95 may indicate redundancy (overlapping items) rather than genuine reliability — consider trimming items.
📖 References
- Cronbach, L. J. (1951). Coefficient alpha and the internal structure of tests. Psychometrika, 16(3), 297–334. doi:10.1007/BF02310555
- Feldt, L. S. (1965). The approximate sampling distribution of Kuder-Richardson reliability coefficient twenty. Psychometrika, 30(3), 357–370. doi:10.1007/BF02289499
- Nunnally, J. C. (1978). Psychometric Theory (2nd ed.). New York: McGraw-Hill. ISBN 978-0-07-047465-9.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2Sample Size Calculator — 20 designs
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Sample Size Calculation หาขนาดตัวอย่างขั้นต่ำที่ทำให้การศึกษามี power เพียงพอ (โดยทั่วไป 80% หรือ 90%) ในการตรวจพบ effect ขนาดที่กำหนด ที่ระดับนัยสำคัญ α (มักเป็น 0.05). กรอบทฤษฎีโดย Cohen (1988). DAPH รองรับ 20 design ที่ใช้บ่อยในงานวิจัยด้านสาธารณสุข — แต่ละ design ในหัวข้อย่อยด้านล่างมีสูตรเฉพาะ และมีตัวอย่างการแทนค่าตัวเลขจริง เพื่อให้นักวิจัยตรวจสอบและทำซ้ำได้
Sample Size Calculation finds the minimum n that gives a study adequate power (typically 80% or 90%) to detect a specified effect at significance α (usually 0.05). Foundational framework by Cohen (1988). DAPH supports the 20 designs most often used in public-health research — each sub-section below presents the design-specific formula and a worked numerical example so that researchers can verify and reproduce the calculation.
11.2.1One-sample mean (test μ vs known μ₀)
ใช้เมื่อต้องการทดสอบว่าค่าเฉลี่ยของตัวอย่างต่างจากค่ามาตรฐานหรือค่าอ้างอิงที่ทราบแล้ว (เช่น ค่าเฉลี่ยประชากร, ค่ามาตรฐานทางคลินิก)
Use when testing whether a sample mean differs from a known reference (e.g. population norm, clinical benchmark).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05; 2.58 ที่ α=0.01)z-quantile for α (= 1.96 at α=0.05; 2.58 at α=0.01)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80; 1.28 ที่ power=0.90)z-quantile for power 1−β (= 0.84 at power=0.80; 1.28 at power=0.90)
- μ, μ₀
- mean ที่คาดหวัง, mean อ้างอิงexpected mean, reference mean
- σ
- standard deviation ของ outcomestandard deviation of the outcome
โจทย์: ค่าเฉลี่ย BMI ของผู้ป่วยในคลินิกหัวใจล้มเหลวต่างจากค่าเฉลี่ยประชากรไทย (μ₀ = 24.0 kg/m²) หรือไม่? คาด μ = 25.5, σ = 4.0, α = 0.05 (two-sided), power = 80%
Scenario: Does mean BMI in a heart-failure clinic differ from the Thai population mean (μ₀ = 24.0 kg/m²)? Expect μ = 25.5, σ = 4.0, α = 0.05 (two-sided), power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed., Ch. 2). Hillsdale, NJ: Lawrence Erlbaum Associates. ISBN 978-0-8058-0283-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.2Two-sample mean (independent t-test)
ใช้เมื่อเปรียบเทียบ mean ของ outcome ต่อเนื่องระหว่าง 2 กลุ่มที่อิสระต่อกัน (RCT, cohort, cross-sectional)
Use when comparing the mean of a continuous outcome between two independent groups (RCT, cohort, cross-sectional).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- δ
- ผลต่าง mean ที่คาดหวัง (mean group 1 − mean group 2)expected difference in means (group 1 − group 2)
- σ
- standard deviation (สมมุติเท่ากันทั้ง 2 กลุ่ม)standard deviation (assumed equal for both groups)
- dCohen
- effect size · 0.2 small, 0.5 medium, 0.8 largeeffect size · 0.2 small, 0.5 medium, 0.8 large
โจทย์: เปรียบเทียบการลด HbA1c ระหว่างยา A vs B (RCT). คาดผลต่าง δ = 0.6%, σ = 1.5%, α = 0.05 (two-sided), power = 80%
Scenario: Compare HbA1c reduction between drugs A and B (RCT). Expected mean diff δ = 0.6%, σ = 1.5%, α = 0.05 (two-sided), power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed., Ch. 2). Hillsdale, NJ: Lawrence Erlbaum Associates. ISBN 978-0-8058-0283-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.3Paired mean (paired t-test, pre-post)
ใช้เมื่อวัด outcome ซ้ำในคนเดียวกัน 2 ครั้ง (ก่อน-หลังการรักษา, baseline-followup)
Use when an outcome is measured twice in the same subjects (pre vs post, baseline vs follow-up).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- δ
- ค่าเฉลี่ยของผลต่างจับคู่ที่คาดหวัง (post − pre)expected mean paired difference (post − pre)
- σd
- s.d. ของผลต่างจับคู่ (ปกติเล็กกว่า σ ของ raw data)s.d. of paired differences (usually smaller than raw σ)
โจทย์: น้ำหนักก่อน-หลังโปรแกรมออกกำลังกาย 6 เดือน. คาด δ = 2 kg, σ_d = 4 kg, α = 0.05, power = 80%
Scenario: Pre-post weight after a 6-month exercise programme. Expect δ = 2 kg, σ_d = 4 kg, α = 0.05, power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed., Ch. 2). Hillsdale, NJ: Lawrence Erlbaum Associates. ISBN 978-0-8058-0283-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.4One-sample proportion (test π vs known π₀)
ใช้เมื่อทดสอบว่าสัดส่วนในกลุ่มเดียวต่างจากค่าอ้างอิง (เช่น prevalence ระดับชาติ, เกณฑ์ WHO)
Use when testing whether a single proportion differs from a known reference (e.g. national prevalence, WHO benchmark).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- π0
- สัดส่วนอ้างอิง (null hypothesis)reference proportion (null hypothesis)
- p1
- สัดส่วนที่คาดหวังในตัวอย่าง (alternative)expected sample proportion (alternative)
โจทย์: อัตราการฉีดวัคซีน COVID-19 ในอำเภอเป้าหมายสูงกว่าค่าเฉลี่ยประเทศ (π₀ = 0.65) หรือไม่? คาด p = 0.75, α = 0.05, power = 80%
Scenario: Is the COVID-19 vaccination rate in a target district higher than the national average (π₀ = 0.65)? Expect p = 0.75, α = 0.05, power = 80%.
- Fleiss, J. L., Levin, B., & Paik, M. C. (2003). Statistical Methods for Rates and Proportions (3rd ed.). Hoboken, NJ: Wiley. ISBN 978-0-471-52629-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.5Two-sample proportion (independent, Fleiss)
ใช้เมื่อเปรียบเทียบสัดส่วนของเหตุการณ์ระหว่าง 2 กลุ่ม (RCT outcome rate, prevalence study). สูตร Fleiss ที่ปรับ unpooled SE (Casagrande, Pike & Smith 1978; doi:10.2307/2530613)
Use when comparing event proportions across two groups (RCT outcome rate, prevalence study). Fleiss-style formula with unpooled SE (Casagrande, Pike & Smith 1978; doi:10.2307/2530613).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- p1, p2
- สัดส่วนเหตุการณ์ที่คาดหวังในกลุ่ม 1 และ 2expected event proportions in groups 1 and 2
- p̄, q̄
- ค่าเฉลี่ยรวม (p₁+p₂)/2 และ 1−p̄pooled mean (p₁+p₂)/2 and 1−p̄
โจทย์: เปรียบเทียบ case-fatality ของ ICU 2 แห่ง: p₁ = 0.20 vs p₂ = 0.30. α = 0.05, power = 80%
Scenario: Compare ICU case-fatality between two hospitals: p₁ = 0.20 vs p₂ = 0.30. α = 0.05, power = 80%.
- Casagrande, J. T., Pike, M. C., & Smith, P. G. (1978). An improved approximate formula for calculating sample sizes for comparing two binomial distributions. Biometrics, 34(3), 483–486. doi:10.2307/2530613
- Fleiss, J. L., Levin, B., & Paik, M. C. (2003). Statistical Methods for Rates and Proportions (3rd ed.). Hoboken, NJ: Wiley. ISBN 978-0-471-52629-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.6Paired proportion (McNemar — matched pairs)
ใช้เมื่อเปรียบเทียบสัดส่วนของผลก่อน-หลังหรือ matched case-control 1:1 — ใช้เฉพาะ discordant pairs (Connor 1987; doi:10.2307/2531961)
Use when comparing pre-post proportions or 1:1 matched case-control — relies on discordant pairs only (Connor 1987; doi:10.2307/2531961).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- p10, p01
- สัดส่วน discordant pairs (เซลล์ b และ c ใน 2×2 paired table)discordant-pair proportions (cells b and c in the 2×2 paired table)
- pd
- = p₁₀ + p₀₁ (สัดส่วน discordant pairs รวม)= p₁₀ + p₀₁ (total discordant-pair proportion)
โจทย์: Test A vs Test B วินิจฉัยใน 200 ผู้ป่วยเดียวกัน. คาด p₁₀ = 0.15 (A+ B−), p₀₁ = 0.05 (A− B+). α = 0.05, power = 80%
Scenario: Test A vs Test B on the same 200 patients. Expect p₁₀ = 0.15 (A+ B−), p₀₁ = 0.05 (A− B+). α = 0.05, power = 80%.
- Connor, R. J. (1987). Sample size for testing differences in proportions for the paired-sample design. Biometrics, 43(1), 207–211. doi:10.2307/2531961
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.7Pearson correlation (test H₀: ρ = 0)
หาขนาดตัวอย่างที่จะพบ correlation r เป็น significant — ใช้ Fisher z-transformation (Bonett & Wright 2000; doi:10.1007/BF02294183)
Find sample size to detect correlation r as significant — uses Fisher z-transformation (Bonett & Wright 2000; doi:10.1007/BF02294183).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- r
- correlation coefficient ที่คาดหวัง (alternative)expected correlation coefficient (alternative)
- ½ ln((1+r)/(1−r))
- Fisher z-transformation ของ rFisher z-transformation of r
โจทย์: ตรวจจับ correlation r = 0.30 ระหว่าง BMI กับ HbA1c. α = 0.05 (two-sided), power = 80%
Scenario: Detect correlation r = 0.30 between BMI and HbA1c. α = 0.05 (two-sided), power = 80%.
- Bonett, D. G., & Wright, T. A. (2000). Sample size requirements for estimating Pearson, Kendall and Spearman correlations. Psychometrika, 65(1), 23–28. doi:10.1007/BF02294183
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.8Linear regression (R² / partial-R² test)
ทดสอบว่า set ของ predictor อธิบาย y ได้อย่างมีนัยสำคัญ; ใช้ Cohen's f² (small 0.02, medium 0.15, large 0.35)
Test whether a set of predictors explains y significantly; uses Cohen's f² (small 0.02, medium 0.15, large 0.35).
- u, k
- จำนวน predictor ที่ทดสอบ; k = จำนวน predictor รวมในโมเดลnumber of tested predictors; k = total predictors in the model
- R²
- coefficient of determination ที่คาดหวังexpected coefficient of determination
- f²
- Cohen's effect size · 0.02 small, 0.15 medium, 0.35 largeCohen's effect size · 0.02 small, 0.15 medium, 0.35 large
- L
- non-centrality parameter ของ F-distribution (≈ 7.85 ถึง 14.17 ขึ้นกับ u, α, power · ดู Cohen 1988 Table 9.4.2)non-centrality parameter of the F-distribution (≈ 7.85 to 14.17 depending on u, α, power · see Cohen 1988 Table 9.4.2)
โจทย์: ทดสอบ multiple regression ที่มี predictor 4 ตัว, expected R² = 0.13. α = 0.05, power = 80%
Scenario: Multiple regression with 4 predictors, expected R² = 0.13. α = 0.05, power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed., Ch. 9). Hillsdale, NJ: Lawrence Erlbaum Associates. ISBN 978-0-8058-0283-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.9Logistic regression (univariable & multivariable)
ทดสอบว่า predictor (continuous หรือ binary) สัมพันธ์กับ outcome แบบ OR ≠ 1. Hsieh, Bloch & Larsen (1998) เสนอสูตรพื้นฐานสำหรับ univariable และต้องคูณด้วย variance inflation factor (VIF) = 1/(1−ρ²) เพื่อปรับเป็น multivariable เมื่อ predictor of interest มี correlation กับ covariate อื่นในโมเดล
Test whether a predictor (continuous or binary) is associated with the outcome (OR ≠ 1). Hsieh, Bloch & Larsen (1998) derived the basic univariable formula and added a variance inflation factor (VIF) = 1/(1−ρ²) for the multivariable case, where ρ² is the squared multiple correlation of the predictor of interest with the other covariates.
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- OR
- odds ratio ต่อ 1 SD ของ X (continuous) หรือ vs reference (binary)odds ratio per 1 SD of X (continuous) or vs reference (binary)
- P
- overall event probability ของ outcomeoverall event probability of the outcome
- σX
- s.d. ของ X (= 1 ถ้า X standardised; ใช้ √[B(1−B)] ถ้า X เป็น binary prevalence B)s.d. of X (= 1 if X standardised; use √[B(1−B)] for binary X with prevalence B)
- ρ²
- squared multiple correlation ระหว่าง X (predictor of interest) กับ covariate อื่นในโมเดล · ค่าจาก pilot study หรือ literaturesquared multiple correlation between X (predictor of interest) and other covariates · estimate from pilot data or literature
- VIF
- Variance Inflation Factor · ≈ 1 ถ้า predictor อิสระ, > 1 ถ้ามี collinearity (VIF > 5 = collinearity แรง)Variance Inflation Factor · ≈ 1 if predictor is independent, > 1 with collinearity (VIF > 5 = strong)
โจทย์: ตรวจจับ OR = 1.5 ต่อ 1-SD ของ X, P = 0.20, σ_X = 1, α = 0.05, power = 80%. (1) univariable, และ (2) multivariable เมื่อ X correlate กับ covariate อื่น ρ² = 0.30
Scenario: Detect OR = 1.5 per 1-SD of X, P = 0.20, σ_X = 1, α = 0.05, power = 80%. (1) univariable, and (2) multivariable when X correlates with other covariates with ρ² = 0.30.
- Hsieh, F. Y., Bloch, D. A., & Larsen, M. D. (1998). A simple method of sample size calculation for linear and logistic regression. Statistics in Medicine, 17(14), 1623–1634. doi:10.1002/(SICI)1097-0258(19980730)17:14<1623::AID-SIM871>3.0.CO;2-S
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.10One-way ANOVA (k groups, Cohen's f)
เปรียบเทียบ mean ระหว่าง ≥3 กลุ่ม. Cohen's f: small 0.10, medium 0.25, large 0.40
Compare means across ≥3 groups. Cohen's f: small 0.10, medium 0.25, large 0.40.
- k, N
- จำนวนกลุ่ม, ขนาดตัวอย่างรวมnumber of groups, total sample size
- μk, μ̄, σ
- mean ของกลุ่ม k, grand mean, ค่า s.d. ของ outcomegroup k mean, grand mean, s.d. of outcome
- f
- Cohen's f effect size · 0.10 small, 0.25 medium, 0.40 largeCohen's f effect size · 0.10 small, 0.25 medium, 0.40 large
- λ
- non-centrality parameter ของ F-distribution (ดู Cohen 1988 Table 8.4.4)non-centrality parameter of the F-distribution (see Cohen 1988 Table 8.4.4)
โจทย์: เปรียบเทียบ BMI ระหว่าง 4 BMI category (k = 4). คาด f = 0.25 (medium). α = 0.05, power = 80%
Scenario: Compare BMI across 4 categories (k = 4). Expect f = 0.25 (medium). α = 0.05, power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed., Ch. 8). Hillsdale, NJ: Lawrence Erlbaum Associates. ISBN 978-0-8058-0283-2.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.11Cox PH / Survival
เปรียบเทียบ time-to-event ระหว่าง 2 กลุ่ม — คำนวณ จำนวน events ที่ต้องการก่อน แล้วหารด้วย expected event rate (Schoenfeld 1983; doi:10.2307/2531021)
Compare time-to-event between two arms — compute required events first, then divide by expected event rate (Schoenfeld 1983; doi:10.2307/2531021).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- HR
- hazard ratio ที่คาดหวัง (treatment vs control)expected hazard ratio (treatment vs control)
- p1, p2
- สัดส่วน allocation (= 0.5 ทั้งคู่ ถ้า 1:1)allocation proportions (= 0.5 each for 1:1)
- d
- จำนวน events ที่ต้องการ (required deaths/events)required events (deaths)
- ē
- expected event rate เฉลี่ยทั้งสอง arm ณ ระยะเวลา follow-upexpected event rate averaged across both arms over follow-up
โจทย์: RCT ยาใหม่ vs control. HR = 0.70, 5-yr mortality control = 40%. Allocation 1:1, α = 0.05, power = 80%
Scenario: RCT new drug vs control. HR = 0.70, 5-yr mortality in control = 40%. Allocation 1:1, α = 0.05, power = 80%.
- Schoenfeld, D. A. (1983). Sample-size formula for the proportional-hazards regression model. Biometrics, 39(2), 499–503. doi:10.2307/2531021
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.12Diagnostic test (Sens / Spec CI half-width)
หาขนาด กลุ่มผู้ป่วย (D+) เพื่อให้ Sens มี 95% CI กว้าง ±w; ใช้ prevalence ของโรคในประชากรเพื่อแปลงเป็น n ทั้งหมด (Buderer 1996; doi:10.1111/j.1553-2712.1996.tb03538.x)
Find the diseased subset (D+) needed so Sens has 95% CI of ±w; use disease prevalence to convert to total n (Buderer 1996; doi:10.1111/j.1553-2712.1996.tb03538.x).
- z1−α/2
- z-quantile สำหรับระดับความเชื่อมั่น (= 1.96 ที่ 95% CI)z-quantile for the confidence level (= 1.96 for 95% CI)
- Sens, Spec
- sensitivity / specificity ที่คาดหวัง (เป็นสัดส่วน 0–1)expected sensitivity / specificity (proportion 0–1)
- w
- ความกว้างครึ่งหนึ่งของ CI (precision target · เช่น 0.05 = ±5%)CI half-width (precision target · e.g. 0.05 = ±5%)
- prevalence
- ความชุกของโรคในประชากรเป้าหมายdisease prevalence in the target population
- nD+
- จำนวนผู้ป่วยที่ต้องการ (เพื่อประมาณ Sens), nD− ทำคล้ายกันสำหรับ Specrequired number of diseased subjects (for Sens estimation); nD− analogous for Spec
โจทย์: Validate การตรวจ TB ใหม่. ต้องการ Sens = 0.90 ที่ 95% CI ±5% (w = 0.05). Prevalence ของ TB ใน setting = 5%
Scenario: Validate a new TB test. Target Sens = 0.90 with 95% CI ±5% (w = 0.05). TB prevalence in the setting = 5%.
- Buderer, N. M. F. (1996). Statistical methodology: I. Incorporating the prevalence of disease into the sample size calculation for sensitivity and specificity. Academic Emergency Medicine, 3(9), 895–900. doi:10.1111/j.1553-2712.1996.tb03538.x
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.13Ordered Logistic Regression (Proportional Odds)
สำหรับ outcome ที่มีลำดับ ≥ 3 ระดับ (เช่น mild < moderate < severe) ใช้สมมุติฐาน proportional odds (Whitehead 1993; doi:10.1002/sim.4780122404)
For ordered outcomes with ≥3 levels (e.g., mild < moderate < severe) under the proportional-odds assumption (Whitehead 1993; doi:10.1002/sim.4780122404).
- OR
- proportional odds ratio ที่ต้องการตรวจจับproportional odds ratio to detect
- pj
- สัดส่วนใน category j (รวมทุก j = 1)proportion in category j (Σ = 1)
- A = p₁p₂
- ผลคูณของ allocation (= 0.25 ที่ 1:1)allocation product (= 0.25 at 1:1)
โจทย์: COVID severity 4 ระดับ (mild/moderate/severe/critical) คาด OR = 1.5 ของ vaccine vs unvaccinated · pj = (0.25, 0.35, 0.25, 0.15) · allocation 1:1 · α=.05, power=80%
Scenario: COVID severity in 4 ordered levels (mild/moderate/severe/critical), expected OR = 1.5 vaccine vs unvaccinated, pj = (0.25, 0.35, 0.25, 0.15), 1:1 allocation, α=.05, power=80%.
- Whitehead, J. (1993). Sample size calculations for ordered categorical data. Statistics in Medicine, 12(24), 2257–2271. doi:10.1002/sim.4780122404
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.14Multinomial Logistic Regression (≥3 unordered categories)
outcome > 2 หมวด ไม่มีลำดับ — DAPH คำนวณ n ของแต่ละ contrast (vs reference) ด้วยสูตร Hsieh-style two-proportion แล้วใช้ค่าสูงสุด พร้อม Bonferroni adjust α/(J−1)
Unordered outcome with > 2 categories — DAPH computes n for each contrast (vs reference) using a Hsieh-style two-proportion formula, takes the max, and applies a Bonferroni adjustment α/(J−1).
- J
- จำนวน category ทั้งหมด (รวม reference)total number of categories (including reference)
- ORj
- odds ratio ของ category j vs referenceodds ratio of category j vs reference
- α*
- Bonferroni-adjusted alpha สำหรับ J−1 contrastsBonferroni-adjusted alpha for J−1 contrasts
โจทย์: ชนิดเชื้อปอดบวม 4 หมวด (Strep ref, Mycoplasma, Viral, Fungal) · OR ของ contrasts = (2.0, 1.5, 0.8) · pj = (0.40, 0.30, 0.20, 0.10) · α=.05, power=80%
Scenario: Pneumonia pathogen in 4 categories (Strep=ref, Mycoplasma, Viral, Fungal); OR contrasts = (2.0, 1.5, 0.8); pj = (0.40, 0.30, 0.20, 0.10); α=.05, power=80%.
- Hsieh, F. Y., Bloch, D. A., & Larsen, M. D. (1998). A simple method of sample size calculation for linear and logistic regression. Statistics in Medicine, 17(14), 1623–1634. doi:10.1002/(SICI)1097-0258(19980730)17:14<1623::AID-SIM871>3.0.CO;2-S
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.15Poisson Regression (count outcome)
นับจำนวนเหตุการณ์ต่อหน่วยเวลา/พื้นที่ (เช่น ผู้ป่วยใหม่/เดือน) — ทดสอบ Incidence Rate Ratio (Signorini 1991; doi:10.1093/biomet/78.2.446)
Event counts per time/area unit (e.g., new cases/month) — Incidence Rate Ratio test (Signorini 1991; doi:10.1093/biomet/78.2.446).
- μ0
- อัตราเหตุการณ์พื้นฐานต่อ subjectbaseline event rate per subject
- IRR
- incidence rate ratio ต่อ 1 หน่วย X ที่ต้องการตรวจจับincidence rate ratio per 1-unit X to detect
- σ²X
- variance ของ X (=1 ถ้า standardised; =B(1−B) ถ้า X binary prevalence B)variance of X (=1 if standardized; =B(1−B) for binary X)
โจทย์: ผลของฝนต่อจำนวน DHF/ตำบล/เดือน · μ₀ = 0.10 (10 cases ต่อ 100 ตำบล/เดือน) · IRR = 1.5 ต่อ 1-SD ฝน · σ²X = 1 (standardized) · α=.05, power=80%
Scenario: Rainfall effect on monthly DHF/sub-district · μ₀ = 0.10 (10 cases/100 sub-districts/month) · IRR = 1.5 per 1-SD rainfall · σ²X = 1 · α=.05, power=80%.
- Signorini, D. F. (1991). Sample size for Poisson regression. Biometrika, 78(2), 446–450. doi:10.1093/biomet/78.2.446
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.16Repeated-Measures ANOVA (longitudinal)
วัด outcome ซ้ำในคนเดียวกัน ≥ 3 timepoints · สูตรสำหรับ between-group main effect ใน longitudinal RCT
Outcome measured repeatedly in the same subjects (≥3 timepoints) · formula for the between-group main effect in longitudinal RCT.
- T
- จำนวน timepoints ที่วัดต่อ subjectnumber of timepoints per subject
- ρ
- within-subject correlation (ปกติ 0.3–0.7)within-subject correlation (typically 0.3–0.7)
- d
- Cohen's d สำหรับ between-group differenceCohen's d for between-group difference
โจทย์: วัดน้ำหนัก 4 timepoints (baseline, 3m, 6m, 12m) · d = 0.4 · ρ = 0.5 · 2 กลุ่ม · α=.05, power=80%
Scenario: Weight at 4 timepoints (baseline, 3m, 6m, 12m), d = 0.4, ρ = 0.5, 2 groups, α=.05, power=80%.
- Diggle, P. J., Heagerty, P., Liang, K.-Y., & Zeger, S. L. (2002). Analysis of Longitudinal Data (2nd ed., Ch. 2). Oxford: Oxford University Press. ISBN 978-0-19-852484-7.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.17GEE / GLMM (Multilevel / Cluster-randomized)
สำหรับข้อมูลที่จัด cluster (ผู้ป่วยใน รพ.เดียวกัน, นักเรียนในห้องเดียวกัน) — คำนวณ n ปกติแล้วคูณด้วย Design Effect
For clustered data (patients within hospitals, students within classes) — compute standard n then multiply by Design Effect.
- niid
- ขนาด two-sample t-test มาตรฐาน (ไม่มี cluster)standard two-sample t-test size (assuming iid)
- m
- ขนาด cluster เฉลี่ย (เช่น 20 ผู้ป่วย/รพ.)average cluster size (e.g., 20 patients/hospital)
- ICC
- intraclass correlation ภายใน cluster (0.01–0.20 ปกติ)intraclass correlation within cluster (typically 0.01–0.20)
- DEFF
- Design Effect (inflation factor)Design Effect (inflation factor)
โจทย์: Cluster-RCT แทรกแซงสุขภาพในระดับ รพ. · d = 0.4 · m = 20 ผู้ป่วย/รพ. · ICC = 0.05 · 2 กลุ่ม · α=.05, power=80%
Scenario: Cluster-RCT at hospital level · d = 0.4 · m = 20 patients/hospital · ICC = 0.05 · 2 groups · α=.05, power=80%.
- Donner, A., & Klar, N. (2000). Design and Analysis of Cluster Randomization Trials in Health Research. London: Arnold. ISBN 978-0-340-69150-0.
- Eldridge, S., & Kerry, S. (2012). A Practical Guide to Cluster Randomised Trials in Health Services Research. Chichester: Wiley. ISBN 978-0-470-51047-5.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.18Chi-square test (goodness-of-fit / independence)
หาขนาดตัวอย่างสำหรับตารางความถี่ — ทดสอบว่าสัดส่วนที่สังเกตต่างจากที่คาดไว้ (goodness-of-fit) หรือสองตัวแปรจัดกลุ่มเป็นอิสระต่อกันหรือไม่ (independence) ใช้ขนาดอิทธิพล w ของ Cohen ร่วมกับการแจกแจงไค-สแควร์แบบ non-central (Cohen 1988, บทที่ 7)
Sizes a frequency table — testing whether observed proportions differ from expected ones (goodness-of-fit) or whether two categorical variables are independent. Uses Cohen's effect size w with the non-central chi-square distribution (Cohen 1988, Ch. 7).
- w
- ขนาดอิทธิพลของ Cohen สำหรับตารางความถี่ · 0.1 = เล็ก, 0.3 = ปานกลาง, 0.5 = ใหญ่Cohen's effect size for frequency tables · 0.1 small, 0.3 medium, 0.5 large
- pobs, pexp
- สัดส่วนในแต่ละช่องที่คาดว่าจะสังเกตได้ (ภายใต้ H₁) และสัดส่วนภายใต้ H₀the cell proportions expected under H₁ and those under H₀
- λ
- non-centrality parameter · เพิ่มเป็นสัดส่วนตรงกับ n จึงเป็นตัวที่ทำให้ power สูงขึ้นเมื่อ n เพิ่มnon-centrality parameter · grows in direct proportion to n, which is what raises power as n increases
- df
- องศาอิสระ = (แถว − 1)(คอลัมน์ − 1) สำหรับ independence · = (จำนวนกลุ่ม − 1) สำหรับ goodness-of-fitdegrees of freedom = (rows − 1)(columns − 1) for independence · = (categories − 1) for goodness-of-fit
โจทย์: ทดสอบความสัมพันธ์ระหว่างระดับการศึกษา (3 กลุ่ม) กับการมารับบริการ (2 กลุ่ม) คาดขนาดอิทธิพลปานกลาง w = 0.3, α = 0.05, power = 80%
Scenario: Test the association between education level (3 groups) and service uptake (2 groups). Expect a medium effect, w = 0.3, α = 0.05, power = 80%.
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.19ANCOVA (two groups, k covariates)
เปรียบเทียบค่าเฉลี่ยสองกลุ่มหลังปรับด้วย covariate — การปรับด้วย covariate ที่สัมพันธ์กับ outcome จะลดความแปรปรวนที่เหลือ ทำให้ต้องใช้ตัวอย่างน้อยลงตามสัดส่วน (1 − ρ²) แล้วบวกคืน 1 หน่วยต่อ covariate 1 ตัวเพื่อชดเชยองศาอิสระที่เสียไป (Borm, Fransen & Lemmens 2007; doi:10.1016/j.jclinepi.2007.02.006)
Compares two group means after adjusting for covariates. Adjusting for a covariate correlated with the outcome shrinks the residual variance, so the required sample falls by a factor of (1 − ρ²); one subject per covariate is then added back to replace the degree of freedom that was spent (Borm, Fransen & Lemmens 2007; doi:10.1016/j.jclinepi.2007.02.006).
- z1−α/2
- z-quantile สำหรับ α (= 1.96 ที่ α=0.05)z-quantile for α (= 1.96 at α=0.05)
- z1−β
- z-quantile สำหรับ power 1−β (= 0.84 ที่ power=0.80)z-quantile for power 1−β (= 0.84 at power=0.80)
- d
- ขนาดอิทธิพล (Cohen's d) ของผลต่างระหว่างกลุ่มหลังปรับ covariateeffect size (Cohen's d) of the adjusted between-group difference
- ρ
- สหสัมพันธ์ระหว่าง covariate กับ outcome · ยิ่งสูงยิ่งลด n ที่ต้องใช้ · ρ = 0 ทำให้ได้ขนาดเท่า t-test ธรรมดาcorrelation between the covariate and the outcome · the higher it is, the smaller the required n · ρ = 0 reduces to the plain t-test size
- k
- จำนวน covariate ในโมเดล · บวกคืน 1 หน่วยต่อ covariate 1 ตัวnumber of covariates in the model · one subject is added back per covariate
โจทย์: ทดลองแบบสุ่มสองกลุ่ม วัดคะแนนคุณภาพชีวิตหลังการทดลอง โดยปรับด้วยคะแนนก่อนการทดลองและอายุ (k = 2) คาด d = 0.5, ρ = 0.5, α = 0.05, power = 80%
Scenario: A two-arm randomised trial measuring a post-intervention quality-of-life score, adjusted for the baseline score and age (k = 2). Expect d = 0.5, ρ = 0.5, α = 0.05, power = 80%.
- Borm, G. F., Fransen, J., & Lemmens, W. A. J. G. (2007). A simple sample size formula for analysis of covariance in randomized clinical trials. Journal of Clinical Epidemiology, 60(12), 1234–1238. doi:10.1016/j.jclinepi.2007.02.006
- Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.2.20Conditional logistic regression (matched case-control)
หาขนาดตัวอย่างสำหรับการศึกษา case-control แบบจับคู่ — การวิเคราะห์แบบมีเงื่อนไขใช้ข้อมูลจาก คู่ที่ไม่สอดคล้องกัน (discordant pairs) เท่านั้น คู่ที่สัมผัสเหมือนกันทั้งคู่ไม่ให้ข้อมูลเลย ขนาดตัวอย่างจึงถูกกำหนดโดยจำนวนคู่ที่ไม่สอดคล้องที่ต้องการ หารด้วยความน่าจะเป็นที่คู่หนึ่งจะไม่สอดคล้องกัน (Schlesselman 1982; Dupont 1988; Ury 1975)
Sizes a matched case-control study. Conditional analysis draws information only from discordant pairs — a pair with the same exposure on both sides contributes nothing — so the sample is set by the number of discordant pairs required, divided by the probability that a pair is discordant (Schlesselman 1982; Dupont 1988; Ury 1975).
- OR
- odds ratio ที่ต้องการตรวจพบthe odds ratio to be detected
- p0
- สัดส่วนการสัมผัสในกลุ่มควบคุมexposure prevalence among controls
- p1
- สัดส่วนการสัมผัสในกลุ่มผู้ป่วย · คำนวณจาก p₀ และ ORexposure prevalence among cases · implied by p₀ and the OR
- pd
- ความน่าจะเป็นที่คู่หนึ่งคู่จะไม่สอดคล้องกัน — มีเพียงคู่แบบนี้ที่ให้ข้อมูลprobability that a pair is discordant — only these pairs carry information
- ψ
- สัดส่วนของคู่ไม่สอดคล้องที่ผู้ป่วยเป็นฝ่ายสัมผัส (ภายใต้ H₀ มีค่า 0.5)the share of discordant pairs in which the case is the exposed one (0.5 under H₀)
- m
- จำนวนคู่ที่ไม่สอดคล้องกันที่ต้องการthe number of discordant pairs required
- M
- จำนวน control ต่อ case 1 ราย · การเพิ่ม control ช่วยลดจำนวน case ที่ต้องใช้ แต่ผลตอบแทนลดลงเรื่อย ๆ หลัง M ≈ 4controls matched to each case · adding controls lowers the number of cases needed, with diminishing returns beyond M ≈ 4
โจทย์: case-control จับคู่ 1:1 คาด OR = 2.0 สัดส่วนการสัมผัสในกลุ่มควบคุม p₀ = 0.30, α = 0.05, power = 80%
Scenario: A 1:1 matched case-control study expecting OR = 2.0 with control exposure p₀ = 0.30, α = 0.05, power = 80%.
- Schlesselman, J. J. (1982). Case-Control Studies: Design, Conduct, Analysis. Oxford University Press.
- Dupont, W. D. (1988). Power calculations for matched case-control studies. Biometrics, 44(4), 1157–1168.
- Ury, H. K. (1975). Efficiency of case-control studies with multiple controls per case. Biometrics, 31(3), 643–649.
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
11.3Regression Diagnostics — VIF, Cook's D, Residuals
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
Regression Diagnostics ตรวจสมมุติฐานของ regression model หลัง fit — multicollinearity, influential observations, residual normality, heteroscedasticity. ขั้นตอนนี้สำคัญทุกครั้งก่อน publish เพราะถ้า assumption ผิด ผลของ regression อาจ bias ทั้งหมด.
Regression Diagnostics verify post-fit regression assumptions — multicollinearity, influential observations, residual normality, heteroscedasticity. Essential before any publication: violated assumptions can bias the entire regression.
2หลักการและสูตรLogic and Formula
- R²_j
- R² จากการ regress X_j บน predictor อื่นR² from regressing X_j on the other predictors
- ŷ_{(-i)}
- predicted values หลังตัด observation ipredicted values after removing observation i
- h_ii
- leverage ของ observation i (จาก hat matrix)leverage of observation i (from the hat matrix)
เกณฑ์ (O'Brien 2007 / Cook 1977): VIF > 5 → multicollinearity น่าสงสัย, VIF > 10 → ปัญหาแน่นอน · Cook's D > 4/n หรือ > 1 → influential · |studentised residual| > 3 → outlier.
Thresholds (O'Brien 2007 / Cook 1977): VIF > 5 suggests multicollinearity, VIF > 10 confirms it · Cook's D > 4/n or > 1 → influential · |studentised residual| > 3 → outlier.
3สคริปต์ R และการทวนสอบกับ DAPHR Script and Verification against DAPH
library(car); data(mtcars)
fit <- lm(mpg ~ hp + wt + disp + cyl, data = mtcars)
vif(fit) # → multicollinearity check
cooks.distance(fit) # → influence
plot(fit, which = c(1,2,3,5)) # residuals + QQ + scale-location + leverage
shapiro.test(residuals(fit)) # normality of residuals
ncvTest(fit) # Breusch-Pagan heteroscedasticity
| Quantity | R car (mtcars) | DAPH | Status |
|---|---|---|---|
| VIF (hp) | match to 1e−3 | match | ✓ PASS |
| max Cook's D | match to 1e−4 | match | ✓ PASS |
| Shapiro W p | match to 1e−4 | match | ✓ PASS |
4การแปลผลและการแก้ปัญหาInterpretation and Remediation
Multicollinearity (VIF สูง): ตัด predictor ที่ซ้ำซ้อน, สร้าง composite score, หรือใช้ ridge/LASSO regression
Influential observation (Cook's D > 1): ตรวจ data entry; ถ้าเป็น outlier จริง รายงานทั้ง with + without observation นั้น
Non-normal residuals: transform y (log, sqrt), ใช้ robust regression, หรือ bootstrap CI
Heteroscedasticity: ใช้ robust (sandwich) SE, weighted least squares, หรือ transform
Multicollinearity (high VIF): drop redundant predictors, build a composite score, or use ridge/LASSO regression
Influential observation (Cook's D > 1): verify data entry; if a real outlier, report with + without it
Non-normal residuals: transform y (log, sqrt), use robust regression, or bootstrap CI
Heteroscedasticity: use robust (sandwich) SEs, weighted least squares, or transform
📖 References
- Cook, R. D. (1977). Detection of influential observation in linear regression. Technometrics, 19(1), 15–18. doi:10.1080/00401706.1977.10489493
- O'Brien, R. M. (2007). A caution regarding rules of thumb for variance inflation factors. Quality & Quantity, 41(5), 673–690. doi:10.1007/s11135-006-9018-6
- Breusch, T. S., & Pagan, A. R. (1979). A simple test for heteroscedasticity and random coefficient variation. Econometrica, 47(5), 1287–1294. doi:10.2307/1911963
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
บทที่ 12 — การเลือกแบบจำลอง (Model Selection)Chapter 12 — Model Selection 📘 ระเบียบวิธีMethod notes
บทนี้รวบรวม ทุกวิธีการเลือกตัวแปรและเลือกแบบจำลองที่ DAPH มีให้เลือกใช้ ไว้ในที่เดียว — ทั้งเจ็ดวิธีของสถิติเชิงพื้นที่ หกวิธีของ Machine Learning และเกณฑ์ที่ใช้ตัดสินโครงสร้างของแบบจำลอง (AIC · BIC · LM · Hausman · ค่าประสิทธิภาพจากข้อมูลทดสอบ) พร้อมระบุว่าสถิติแต่ละตัวเปิดให้ใช้วิธีใดได้บ้าง This chapter gathers every variable-selection and model-selection option DAPH offers in one place — the seven screens used by the spatial statistics, the six used by Machine Learning, and the criteria that decide model STRUCTURE (AIC · BIC · LM · Hausman · held-out performance) — together with a map of which statistic offers which.
12.1หลักการเลือกแบบจำลอง — อธิบาย (explain) กับ ทำนาย (predict)Principles of Model Selection — Explaining vs Predicting
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
คำถามแรกก่อนกดเลือกวิธีใด ๆ ไม่ใช่ "วิธีไหนดีที่สุด" แต่คือ "ตัวแบบนี้จะถูกใช้ทำอะไร" — Shmueli (2010) แยกเป้าหมายไว้สองทางที่นำไปสู่การเลือกคนละแบบ:
(ก) เพื่ออธิบาย (explanatory) — ต้องการค่าสัมประสิทธิ์ที่ตีความได้ เช่น "รายได้ต่ำสัมพันธ์กับอัตราป่วยเพิ่มขึ้นเท่าใด" ตัวแปรที่ใส่ในแบบจำลองจึงมาจาก ทฤษฎีและกรอบแนวคิด เป็นหลัก ตัวแปรกวน (confounder) ต้องคงไว้แม้ไม่มีนัยสำคัญ และไม่ควรให้ขั้นตอนอัตโนมัติตัดออก
(ข) เพื่อทำนาย (predictive) — ต้องการค่าทำนายที่แม่นกับข้อมูลที่ยังไม่เคยเห็น ตัวแปรจึงถูกคัดด้วยเกณฑ์ประสิทธิภาพ และตัดสินด้วย ข้อมูลที่กันไว้ทดสอบ ไม่ใช่ค่าที่คำนวณจากข้อมูลชุดฝึกเอง
The first question is not "which method is best" but "what will this model be used for". Shmueli (2010) separates two goals that lead to different choices:
(a) To explain — you want interpretable coefficients ("how much does low income raise the rate?"). Predictors come primarily from theory; confounders stay in whether or not they reach significance, and no automated step should remove them.
(b) To predict — you want accuracy on data the model has never seen. Predictors are screened on performance, judged on held-out data rather than on the training data itself.
2หลักการและสูตรLogic and Formula
เกณฑ์สารสนเทศ (information criteria) ให้คะแนนแบบจำลองด้วยความพอดีระหว่าง ความแนบข้อมูล กับ จำนวนพารามิเตอร์ — ยิ่งค่าน้อยยิ่งดี:
Information criteria trade fit against the number of parameters — lower is better:
- ℓ̂
- ค่า log-likelihood ที่จุดประมาณค่าสูงสุดmaximised log-likelihood
- k
- จำนวนพารามิเตอร์ที่ประมาณค่า (รวมพจน์เชิงพื้นที่ ρ หรือ λ และค่าความแปรปรวน)number of estimated parameters (including a spatial ρ or λ and the variance term)
- n
- จำนวนหน่วยสังเกตnumber of observations
Burnham & Anderson (2002) ให้กติกาอ่านค่า Δ ไว้ว่า Δ < 2 คือสองแบบจำลองมีหลักฐานสนับสนุนพอ ๆ กัน · Δ 4–7 คือแบบจำลองนั้นด้อยกว่าอย่างชัดเจน · Δ > 10 คือแทบไม่มีหลักฐานสนับสนุนเลย. ข้อควรระวัง: AIC เปรียบเทียบได้เฉพาะแบบจำลองที่ฟิตกับ ข้อมูลชุดเดียวกันและตัวแปรตามตัวเดียวกัน เท่านั้น — ถ้าจำนวนแถวเปลี่ยนเพราะข้อมูลขาดหาย ค่า AIC ของสองแบบจำลองเทียบกันไม่ได้
Burnham & Anderson (2002) read Δ as: < 2 = both models have substantial support · 4–7 = considerably less support · > 10 = essentially none. Caveat: AIC compares only models fitted to the same rows and the same outcome — if missing data changes n, the two AIC values are not comparable.
ตัวแปรเยอะ ตัวอย่างน้อย — ข้อมูลรองรับตัวแปรได้กี่ตัว ไม่มีวิธีคัดเลือกใดสร้างข้อมูลเพิ่มได้ ถ้าจำนวนหน่วยสังเกตน้อยเมื่อเทียบกับจำนวนตัวแปร การคัดเลือกจะกลายเป็นการจับเสียงรบกวน กติกาที่ใช้ได้จริงคือ
- ตัวแปรตามต่อเนื่อง — อย่างน้อยประมาณ 10–15 หน่วยสังเกตต่อพารามิเตอร์ที่ประมาณค่า (Harrell 2015)
- ตัวแปรตามสองทางหรือแบบอยู่รอด — นับที่ จำนวนเหตุการณ์ ไม่ใช่จำนวนแถว: ประมาณ 10 เหตุการณ์ต่อหนึ่งตัวแปร (events per variable; Peduzzi et al. 1996)
- แบบจำลองทำนาย — คำนวณขนาดตัวอย่างขั้นต่ำจากสูตรของ Riley et al. (2020) แทนการใช้กติกา 10 EPV เพียงอย่างเดียว
- สถิติเชิงพื้นที่ — หน่วยสังเกตคือ พื้นที่ ไม่ใช่ประชากรในพื้นที่ ข้อมูลระดับจังหวัด 77 จังหวัดจึงมี n = 77 ไม่ว่าประชากรรวมจะกี่ล้านคน
- Continuous outcome — roughly 10–15 observations per estimated parameter (Harrell 2015).
- Binary or survival outcome — count events, not rows: about 10 events per variable (Peduzzi et al. 1996).
- Prediction models — derive the minimum sample size from Riley et al. (2020) rather than relying on the 10-EPV rule alone.
- Spatial statistics — the observation is the area, not the people in it: 77 provinces means n = 77 however many millions live there.
เมื่อข้อมูลไม่พอ ทางออกที่ปกป้องได้คือ ลดจำนวนตัวแปรที่นำเข้าพิจารณาด้วยกรอบแนวคิดตั้งแต่ต้น หรือใช้วิธีที่มีบทลงโทษ (penalized) ซึ่งออกแบบมาเพื่อสถานการณ์นี้โดยเฉพาะ ไม่ใช่การไล่ตัดด้วย stepwise จนเหลือน้อย ๆ แล้วรายงานเหมือนตั้งไว้ล่วงหน้า
When the data cannot support the candidate set, the defensible response is to narrow the candidates by theory up front, or to use a penalised method built for this situation — not to run a stepwise search down to a small set and then report it as if it had been pre-specified.
3สคริปต์ R ที่เทียบเคียงกันEquivalent R Script
m_full <- lm(y ~ x1 + x2 + x3 + x4, data = d)
m_red <- lm(y ~ x1 + x2, data = d)
AIC(m_full, m_red); BIC(m_full, m_red)
logLik(m_full)
# stepwise by AIC (the criterion DAPH uses — not p-value)
MASS::stepAIC(m_full, direction = "backward") # k = 2 -> AIC
MASS::stepAIC(m_full, direction = "forward",
scope = list(lower = ~1, upper = ~x1+x2+x3+x4))
stepAIC (k = 2) และแสดง log-likelihood · AIC · BIC ไว้ในตารางผลลัพธ์ของทุกแบบจำลองที่ฟิตด้วยวิธี maximum likelihooduses the same AIC criterion as stepAIC (k = 2) and prints log-likelihood · AIC · BIC in the results table of every maximum-likelihood modelหมายเหตุการทวนสอบ: บทนี้เป็นบทระเบียบวิธี — ค่าที่ใช้ตัดสิน (log-likelihood · AIC · BIC · LM · Hausman) ถูกทวนสอบกับ R ไว้แล้วในบทของสถิติแต่ละตัว (บทที่ 6 สำหรับเชิงพื้นที่ · บทที่ 7 สำหรับ Machine Learning) จึงไม่ทำตารางทวนสอบซ้ำในบทนี้
Verification note: this is a methods chapter — the quantities the criteria are built from (log-likelihood · AIC · BIC · LM · Hausman) are verified against R in the chapters of the individual statistics (Chapter 6 for spatial, Chapter 7 for Machine Learning), so the verification tables are not duplicated here.
4สถิติใดเลือกตัวแปรได้ด้วยวิธีใดบ้างWhich Statistic Offers Which Screen
ตารางนี้คือแผนที่ของทั้งบท — ช่องขวาสุดบอกว่าไปอ่านรายละเอียดต่อได้ที่หัวข้อใด
This table is the map of the chapter — the last column points to the section with the details.
| สถิติStatistic | วิธีเลือกตัวแปรที่เลือกได้Selection options | เกณฑ์เลือกโครงสร้างแบบจำลองStructure criterion | รายละเอียดDetails |
|---|---|---|---|
| กลุ่มเชิงพื้นที่ — ดรอปดาวน์ "วิธีเลือกตัวแปร" ในแผงตั้งค่าเชิงพื้นที่Spatial family — the "Variable selection" dropdown in the spatial settings panel | |||
| Spatial Regression OLS · SLM · SEM · SDM |
ครบทั้ง 7 วิธีall 7 screens | AIC / BIC / log-likelihood + การทดสอบ Lagrange Multiplier (กติกาของ Anselin)AIC / BIC / log-likelihood + Lagrange Multiplier tests (Anselin's rule) | 12.2 |
| Spatial Panel Regression Pooled OLS · FE · RE × Lag · Error |
ครบทั้ง 7 วิธีall 7 screens | ทดสอบว่ามีผลประจำพื้นที่หรือไม่ (F test + Breusch–Pagan LM) → Hausman (FE เทียบ RE) → AICtests for area effects (F test + Breusch–Pagan LM) → Hausman (FE vs RE) → AIC | 12.2 |
| กลุ่ม Machine Learning — ดรอปดาวน์ "วิธีเลือกตัวแปร" ในแผงตั้งค่าโมเดลMachine Learning family — the "Variable selection" dropdown in the model settings panel | |||
| Machine Learning Comparison | 6 วิธี (ตัวคัดถูกฟิตใหม่ในทุก fold)6 screens (re-fitted inside every fold) | cross-validation ในข้อมูลฝึกเป็นผู้คัดเลือก · ข้อมูลที่กันไว้ทดสอบเป็นผู้รายงานcross-validation on the training data selects; the held-out set reports | 12.3 |
| Spatial Machine Learning | 6 วิธี6 screens | เหมือนข้างบน แต่แบ่ง fold เป็นบล็อกเชิงพื้นที่as above, but the folds are spatial blocks | 12.3 |
| Spatio-Temporal Machine Learning | 6 วิธี6 screens | เหมือนข้างบน และกันช่วงเวลาท้ายไว้ทดสอบตามลำดับเวลาas above, with the last periods held out in time order | 12.3 |
| กลุ่มถดถอยและทดสอบสมมติฐานทั่วไปRegression and hypothesis-testing family | |||
| Linear · Logistic · Poisson · Cox · Mixed Effect · GEE ฯลฯLinear · Logistic · Poisson · Cox · Mixed Effect · GEE, etc. | Enter เท่านั้น — ตัวแปรที่ผู้ใช้เลือกเข้าแบบจำลองทั้งหมด ไม่มีการตัดอัตโนมัติEnter only — every predictor the user selects goes in; nothing is dropped automatically | ผู้วิจัยตัดสินจากกรอบแนวคิด โดยมีค่าวินิจฉัยประกอบ (VIF · AIC · BIC · Hosmer–Lemeshow ฯลฯ)the researcher decides from theory, supported by the printed diagnostics (VIF · AIC · BIC · Hosmer–Lemeshow, etc.) | 12.1 |
| กลุ่มตัวแปรแฝงและเส้นทางอิทธิพลLatent-variable and path family | |||
| Path Analysis · Factor Analysis · SEM · GSEMPath Analysis · Factor Analysis · SEM · GSEM | ไม่มีการคัดอัตโนมัติ — โครงสร้างเส้นทางและองค์ประกอบมาจากทฤษฎีNo automated screening — the path/measurement structure comes from theory | ดัชนีความกลมกลืน (χ² · CFI · TLI · RMSEA · SRMR) และ AIC/BIC สำหรับเทียบแบบจำลองซ้อนกันfit indices (χ² · CFI · TLI · RMSEA · SRMR) and AIC/BIC for nested comparisons | บทที่ 8–10Ch. 8–10 |
อ่านตารางนี้อย่างไร: ถ้าสถิติที่ใช้ไม่มีดรอปดาวน์ "วิธีเลือกตัวแปร" นั่นไม่ใช่ฟังก์ชันที่ขาดหาย แต่เป็นการออกแบบ — สถิติกลุ่มนั้นใช้เพื่ออธิบายหรือทดสอบสมมติฐานที่ตั้งไว้ล่วงหน้า การให้ขั้นตอนอัตโนมัติมาตัดตัวแปรควบคุมออกจะทำให้ค่าสัมประสิทธิ์ที่เหลือแปลผลไม่ได้
How to read it: a statistic without the dropdown is not missing a feature — it is a design decision. Those statistics answer pre-specified questions, and letting an automated step drop a control variable would leave the surviving coefficients uninterpretable.
📖 References
- Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716–723. doi:10.1109/TAC.1974.1100705
- Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. doi:10.1214/aos/1176344136
- Burnham, K. P., & Anderson, D. R. (2002). Model Selection and Multimodel Inference: A Practical Information-Theoretic Approach (2nd ed.). New York: Springer. ISBN 978-0-387-95364-9.
- Shmueli, G. (2010). To explain or to predict? Statistical Science, 25(3), 289–310. doi:10.1214/10-STS330
- Harrell, F. E. (2015). Regression Modeling Strategies (2nd ed.). Cham: Springer. doi:10.1007/978-3-319-19425-7
- Peduzzi, P., Concato, J., Kemper, E., Holford, T. R., & Feinstein, A. R. (1996). A simulation study of the number of events per variable in logistic regression analysis. Journal of Clinical Epidemiology, 49(12), 1373–1379. doi:10.1016/S0895-4356(96)00236-3
- Riley, R. D., Snell, K. I. E., Ensor, J., et al. (2020). Minimum sample size for developing a multivariable prediction model: Part II — binary and time-to-event outcomes. Statistics in Medicine, 38(7), 1276–1296. doi:10.1002/sim.7992
- Berk, R., Brown, L., Buja, A., Zhang, K., & Zhao, L. (2013). Valid post-selection inference. The Annals of Statistics, 41(2), 802–837. doi:10.1214/12-AOS1077
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
12.2การเลือกตัวแปรใน Spatial Regression และ Spatial Panel Regression — 7 วิธีVariable Selection in Spatial Regression and Spatial Panel Regression — 7 methods
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
ในสถิติเชิงพื้นที่ การเลือกตัวแปรมีข้อจำกัดที่ไม่มีในการถดถอยธรรมดา: พจน์เชิงพื้นที่กับตัวแปรทำนายแย่งกันอธิบายความแปรปรวนชุดเดียวกัน ถ้าตัดตัวแปรที่มีรูปแบบเชิงพื้นที่ออกไป ค่า ρ (spatial lag) หรือ λ (spatial error) จะโตขึ้นมากลืนผลนั้นแทน ทำให้แบบจำลองยังดู "พอดี" ทั้งที่ความหมายเปลี่ยนไปแล้ว
ด้วยเหตุนี้ DAPH จึง ฟิตแบบจำลองเชิงพื้นที่ใหม่ทุกก้าวของการคัดเลือก (ไม่ใช่คัดด้วยการถดถอยธรรมดาแล้วค่อยใส่พจน์เชิงพื้นที่ทีหลัง) และ ตัดสินด้วย AIC ไม่ใช่ p-value เพราะ p-value ในแบบจำลองเชิงพื้นที่มีอคติจากการที่ ρ/λ ดูดซับผลของตัวแปรที่ถูกตัดออกไป
Spatial models add a constraint ordinary regression does not have: the spatial term and the predictors compete for the same variation. Drop a predictor that has spatial structure and ρ (lag) or λ (error) simply grows to absorb it — the model still looks well-fitted while meaning something different.
DAPH therefore refits the spatial model at every step of the search (rather than screening with an ordinary regression and adding the spatial term afterwards) and decides on AIC, not on the p-value, because in a spatial model the p-value is biased by exactly that absorption.
2ทั้งเจ็ดวิธี — หลักการและสูตรThe Seven Methods — Logic and Formula
ดรอปดาวน์เรียงจาก วิธีที่ปกป้องได้มากที่สุดไปหาน้อยที่สุด โดยมี Enter อยู่ท้ายสุด
The dropdown is ordered from the most defensible to the least, with Enter last.
| ลำดับ · ชื่อในระบบOrder · label in DAPH | ทำอะไรWhat it does | ควรใช้เมื่อใดWhen to use |
|---|---|---|
| 1 · คัด collinearity (VIF) → Backward ด้วย AIC (แนะนำ)VIF screen → Backward (AIC) (recommended) | ตัดตัวแปรที่ซ้ำซ้อนกันเชิงเส้นออกก่อน (ตัวแปรกลุ่มนี้ทำให้ค่าสัมประสิทธิ์ไม่เสถียร และอาจแบ่งผลของตัวแปรเดียวไปอยู่สองตัว) จากนั้นทยอยตัดตัวแปรทีละตัวโดยฟิตแบบจำลองเชิงพื้นที่ใหม่ทุกก้าว แล้วเก็บชุดที่ AIC ต่ำที่สุดCollinear predictors are removed first (they make the surviving coefficients unstable and can split one effect across two variables), then predictors are dropped one at a time while the spatial model is refitted at every step, keeping the set with the lowest AIC. | ค่าเริ่มต้นที่เหมาะกับงานส่วนใหญ่ โดยเฉพาะเมื่อตัวแปรทำนายมีหลายตัวที่วัดสิ่งใกล้เคียงกันThe sensible default, especially when several predictors measure closely related things. |
| 2 · คัดกรองด้วย LASSO → Backward ด้วย AICLASSO screen → Backward (AIC) | ใช้ penalized regression บีบสัมประสิทธิ์ของตัวแปรที่อ่อนให้เป็นศูนย์ แล้วส่งตัวที่เหลือเข้าสู่การคัดด้วย AICA penalised fit shrinks weak predictors to exactly zero and hands the survivors to the AIC search. | ตัวแปรทำนายมีจำนวนมากเมื่อเทียบกับจำนวนพื้นที่ จนการค้นแบบ backward อย่างเดียวช้าหรือไม่เสถียรMany candidate predictors relative to the number of areas, where a pure backward search is slow or unstable. |
| 3 · คัดกรองด้วย LASSO (penalized regression)LASSO / Elastic Net screen | penalized regression จัดการตัวแปรจำนวนมากพร้อมกันได้ และไม่มีอคติแบบ stepwise ที่คัดด้วย p-valuePenalised regression handles many candidate predictors at once and does not suffer the selection bias of p-value stepwise. | ต้องการคัดครั้งเดียวจบ ไม่ต้องการการค้นทีละก้าวA single-pass screen without a step-by-step search. |
| 4 · Backward elimination ด้วย AICBackward elimination (AIC) | ตัดตัวแปรทีละตัวโดยฟิตแบบจำลองเชิงพื้นที่ใหม่ทุกก้าว ตัดสินด้วย AIC ไม่ใช่ p-valuePredictors are dropped one at a time, refitting the spatial model at every step; AIC decides, not the p-value. | ตัวแปรไม่มากและไม่มีปัญหา collinearity รุนแรงA moderate predictor set without severe collinearity. |
| 5 · Forward selection ด้วย AICForward selection (AIC) | เพิ่มตัวแปรทีละตัว โดยเลือกตัวที่ทำให้ AIC ลดลงมากที่สุด จนกว่าจะไม่มีตัวใดช่วยให้ AIC ลดลงอีกPredictors are added one at a time, keeping the addition that lowers AIC most, until none does. | จำนวนพื้นที่น้อยจนฟิตแบบจำลองชุดเต็มไม่ได้ตั้งแต่ต้นToo few areas to fit the full model at all. |
| 6 · คัด collinearity ด้วย VIF อย่างเดียวVIF screen only (collinearity) | ตัดเฉพาะตัวแปรที่ซ้ำซ้อนกันเชิงเส้น ตัวแปรอื่นคงไว้ทั้งหมดOnly collinear predictors are removed; everything else is kept. | งานแบบอธิบาย — ตัวคัดนี้ไม่มองตัวแปรตามเลย จึงไม่สร้างอคติต่อค่าสัมประสิทธิ์ที่รายงานExplanatory work — this screen never looks at the outcome, so it cannot bias the reported coefficients. |
| 7 · Enter — ใส่ตัวแปรทั้งหมดEnter — keep every predictor | คงตัวแปรที่เลือกไว้ทั้งหมดในแบบจำลองEvery selected predictor stays in the model. | เมื่อชุดตัวแปรมาจากกรอบแนวคิดและต้องรายงานครบตามที่ตั้งไว้ล่วงหน้าWhen the predictor set is pre-specified by theory and must be reported in full. |
- Rj²
- ค่า R² จากการถดถอยตัวแปรทำนายตัวที่ j ด้วยตัวแปรทำนายที่เหลือ — ยิ่งอธิบายกันเองได้มาก VIF ยิ่งสูงR² from regressing predictor j on the remaining predictors — the better they explain each other, the higher the VIF
- λ
- ความแรงของบทลงโทษ · สัมประสิทธิ์ที่ถูกบีบจนเป็นศูนย์พอดีคือตัวแปรที่ถูกคัดออกpenalty strength; coefficients shrunk to exactly zero are the dropped predictors
- α
- สัดส่วนบทลงโทษแบบ L1 (α = 1 คือ LASSO เต็มรูปแบบ)the L1 share of the penalty (α = 1 is pure LASSO)
เมื่อใดจึงควรแปลผลด้วย SDM (Spatial Durbin)When the Spatial Durbin Model is the one to interpret
SDM เป็นแบบจำลองที่ครอบแบบจำลองอื่นไว้ทั้งหมด (y = ρWy + Xβ + WXθ + ε) ดังนั้น จึงตัดสินด้วยการทดสอบว่าข้อจำกัดที่ทำให้ SDM ยุบเป็นแบบจำลองย่อยถูกปฏิเสธหรือไม่ ตามยุทธศาสตร์ general-to-specific ของ Elhorst (2010) ไม่ใช่ตัดสินว่า "ติ๊กมาก็ใช้ตัวนั้น"
| Wald: θ = 0 | Wald: common factor (θ + ρβ = 0)Wald: common factor (θ + ρβ = 0) | แบบจำลองที่นำมาแปลผลModel to interpret |
|---|---|---|
| ปฏิเสธrejected | ปฏิเสธrejected | SDM — ยุบเป็นแบบจำลองย่อยไม่ได้ทั้งสองทาง และ ต้องแปลผลผ่านการแยกผลของ LeSage–Pace (ทางตรง / ข้ามพื้นที่ / รวม) ไม่ใช่ค่าสัมประสิทธิ์ดิบ เพราะเมื่อมี ρ อยู่ในสมการ ค่าสัมประสิทธิ์ไม่ใช่ผลกระทบส่วนเพิ่มอีกต่อไปneither simplification holds; interpret via the LeSage–Pace direct / spillover / total effects, not the raw coefficients — with ρ in the equation a coefficient is no longer a marginal effect |
| ไม่ปฏิเสธnot rejected | ปฏิเสธrejected | SLM — พจน์ W×X ไม่เพิ่มคำอธิบายthe W×X terms add nothing |
| ปฏิเสธrejected | ไม่ปฏิเสธnot rejected | SEM — SDM ยุบเป็น SEM ได้ ความสัมพันธ์อยู่ในส่วนคลาดเคลื่อนthe SDM collapses to the SEM; the dependence sits in the errors |
| ไม่ปฏิเสธnot rejected | ไม่ปฏิเสธnot rejected | แบบจำลองย่อยเพียงพอทั้งคู่ → ตัดสินตาม LM cascade และถ้า LM ไม่ชี้ขาดด้วย จึงใช้ AIC/BIC ในบรรดาแบบจำลองเชิงพื้นที่both nested models are adequate → follow the LM cascade; if that is mute too, compare the spatial models on AIC/BIC |
ข้อควรจำสองข้อ: (1) ตารางผลกระทบ LeSage–Pace ผูกกับ SDM หากการทดสอบเลือกแบบจำลองย่อยมาแปลผล ตารางนั้นเป็นข้อมูลประกอบเพื่อเปรียบเทียบเท่านั้น ไม่ใช่ค่าที่นำไปอ้างในผลการวิจัย (2) LeSage และ Pace (2009) เสนอว่า SDM เป็นตัวเลือกที่ปลอดภัยเมื่อสงสัยว่ามีตัวแปรที่ไม่ได้วัดซึ่งเกาะกลุ่มเชิงพื้นที่และสัมพันธ์กับตัวแปรทำนาย เพราะแบบจำลองย่อยจะให้ค่าประมาณที่ลำเอียงในกรณีนั้น
Two things to remember: (1) the LeSage–Pace effects table belongs to the SDM — if the tests retained a nested model, that table is context for comparison, not a result to quote; (2) LeSage and Pace (2009) argue the SDM is the safe choice when omitted variables are suspected to be spatially clustered and correlated with the included predictors, since the nested models are then biased.
ขั้นตอนของการค้นด้วย AIC — ในแต่ละก้าว ระบบจะฟิตแบบจำลองเชิงพื้นที่ที่ผู้ใช้เลือก (Lag / Error / Durbin หรือ FE / RE) ใหม่ทั้งหมดสำหรับผู้สมัครแต่ละราย เปรียบเทียบ AIC แล้วจึงเลือกก้าวที่ดีที่สุด ทำซ้ำจนไม่มีก้าวใดทำให้ AIC ลดลงอีก. ระบบคงตัวแปรไว้อย่างน้อยหนึ่งตัวเสมอ และ ชุดตัวแปรที่คัดได้จะถูกใช้กับทุกแบบจำลองที่ติ๊กเลือกไว้ เพื่อให้ตารางเปรียบเทียบอ่านได้ตรงกัน (รวมถึง Spatial Durbin Model ที่ใช้ชุดเดียวกันนี้สร้างพจน์ WX)
How the AIC search runs — at each step every candidate model is refitted in full with the spatial specification the user chose (Lag / Error / Durbin, or FE / RE), the AICs are compared, and the best step is taken; the search stops when no step lowers AIC. At least one predictor is always kept, and the selected set is applied to every ticked model so the comparison table stays readable (the Spatial Durbin Model builds its WX terms from the same set).
3สคริปต์ R ที่เทียบเคียงกันEquivalent R Script
library(spatialreg); library(spdep); library(glmnet); library(car)
W <- nb2listw(poly2nb(shp), style = "W")
# 6 — VIF screen only
car::vif(lm(y ~ x1 + x2 + x3 + x4, data = d)) # drop VIF > 10, iteratively
# 3 — LASSO / Elastic Net screen
cv <- cv.glmnet(as.matrix(d[, xs]), d$y, alpha = 1)
xs_keep <- rownames(coef(cv, s = "lambda.1se"))[which(coef(cv, s = "lambda.1se") != 0)]
# 4 — backward by AIC, REFITTING the spatial model at each step
aic_of <- function(f) AIC(lagsarlm(f, data = d, listw = W))
# ... drop the predictor whose removal lowers aic_of() most; repeat.
# the fitted comparison DAPH reports
AIC(lagsarlm(y ~ ., data = d, listw = W)) # SLM
AIC(errorsarlm(y ~ ., data = d, listw = W)) # SEM
lm.LMtests(lm(y ~ ., data = d), W, test = "all") # LM / robust LM
4การแปลผลและการรายงานInterpretation and Reporting
ในระเบียบวิธีวิจัย ให้ระบุสามอย่างเสมอ: (1) ชุดตัวแปรที่นำเข้าพิจารณาตั้งแต่ต้น (2) วิธีคัดเลือกและเกณฑ์ที่ใช้ตัดสิน (AIC) (3) ชุดตัวแปรที่เหลือในแบบจำลองสุดท้าย — การรายงานเฉพาะข้อ (3) ทำให้ผู้อ่านเข้าใจผิดว่าตัวแปรชุดนี้ถูกตั้งไว้ล่วงหน้า
เมื่อใช้การคัดอัตโนมัติ ควรรายงานแบบจำลองชุดเต็มควบคู่ไปด้วยเป็นการวิเคราะห์ความไว หากผลของตัวแปรหลักเปลี่ยนไปมากระหว่างสองแบบจำลอง นั่นคือข้อค้นพบที่ต้องอภิปราย ไม่ใช่สิ่งที่ควรซ่อน
The methods section must state three things: (1) the candidate set considered, (2) the selection procedure and its criterion (AIC), and (3) the final set. Reporting only (3) misleads the reader into thinking the set was pre-specified.
When an automated screen is used, report the full model alongside as a sensitivity analysis. If the main effect moves substantially between the two, that is a finding to discuss, not something to hide.
สิ่งที่ระบบพิมพ์ให้อัตโนมัติ: บรรทัดสรุปวิธีเลือกตัวแปร ตัวแปรที่ถูกตัด และข้อความเตือน post-selection จะปรากฏทั้งในหน้าผลลัพธ์และในไฟล์รายงานเสมอ ไม่ต้องพิมพ์เพิ่มเอง
Printed automatically: the selection summary, the dropped variables, and the post-selection caveat appear in both the results view and the report file — no need to add them by hand.
📖 References
- Anselin, L. (1988). Spatial Econometrics: Methods and Models. Dordrecht: Kluwer Academic. doi:10.1007/978-94-015-7799-1
- Tibshirani, R. (1996). Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society: Series B, 58(1), 267–288. doi:10.1111/j.2517-6161.1996.tb02080.x
- Zou, H., & Hastie, T. (2005). Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society: Series B, 67(2), 301–320. doi:10.1111/j.1467-9868.2005.00503.x
- Elhorst, J. P. (2014). Spatial Econometrics: From Cross-Sectional Data to Spatial Panels. Berlin: Springer. doi:10.1007/978-3-642-40340-8
- LeSage, J., & Pace, R. K. (2009). Introduction to Spatial Econometrics. Boca Raton: Chapman & Hall/CRC. doi:10.1201/9781420064254
- O'Brien, R. M. (2007). A caution regarding rules of thumb for variance inflation factors. Quality & Quantity, 41(5), 673–690. doi:10.1007/s11135-006-9018-6
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
12.3การคัดตัวแปรใน Machine Learning — 6 วิธี (ฟิตใหม่ในทุก fold)Variable Selection in Machine Learning — 6 methods (re-fitted inside every fold)
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
การคัดตัวแปรในงานทำนายมีกับดักที่ร้ายแรงกว่าในงานอธิบาย: ถ้าคัดตัวแปรครั้งเดียวจากข้อมูลทั้งก้อนแล้วค่อยทำ cross-validation ค่าประสิทธิภาพทุกตัวจะดีเกินจริง เพราะแถวที่ถูกกันไว้ตรวจสอบได้มีส่วนช่วยเลือกตัวแปรไปแล้ว Ambroise & McLachlan (2002) แสดงให้เห็นชัดว่าวิธีนี้ทำให้ ข้อมูลที่เป็นเพียงค่าสุ่มล้วน ๆ ยังรายงานความคลาดเคลื่อนใกล้ศูนย์ได้
DAPH จึงบังคับให้ ตัวคัดตัวแปรเป็นส่วนหนึ่งของสายการประมวลผล — ในทุก fold ตัวคัดจะถูกฟิตใหม่จากข้อมูลฝึกของ fold นั้นเท่านั้น เช่นเดียวกับตัวเติมค่าขาดหายและตัวปรับมาตราส่วน แถวที่กันไว้ตรวจสอบจึงไม่เคยมีส่วนในการเลือกตัวแปรเลย
Feature selection in a prediction study has a sharper trap than in an explanatory one: screen once on the whole dataset and then cross-validate, and every reported metric is optimistic, because the held-out rows already helped choose the predictors. Ambroise & McLachlan (2002) showed this reports near-zero error on pure noise.
DAPH therefore makes the selector part of the pipeline: inside every fold it is re-fitted on that fold's training rows only — exactly like the imputer and the scaler — so the held-out rows never participate in choosing the predictors.
2ทั้งหกวิธี และตารางจับคู่ของโหมด "อัตโนมัติ"The Six Methods and the "Auto" Family Table
| ชื่อในระบบLabel in DAPH | ทำอะไรWhat it does | มองตัวแปรตามหรือไม่Uses the outcome? |
|---|---|---|
| Enter — ใส่ตัวแปรทั้งหมด (ค่าเริ่มต้น)Enter — keep every predictor (default) | ตัวแปรทุกตัวเข้าแบบจำลอง ปล่อยให้ regularisation ของโมเดลเองจัดการ ซึ่งเป็นแนวทางที่ใช้กันมากที่สุดในงานสร้างแบบจำลองทำนายEvery predictor goes in; the model's own regularisation does the work — the usual choice for prediction models. | ไม่No |
| อัตโนมัติ — เลือกตัวคัดให้เหมาะกับแต่ละโมเดล (แนะนำ)Auto — match the screen to each model (recommended) | จับคู่ตัวคัดกับ ตระกูล ของโมเดลที่มันป้อนให้ ตามตารางด้านล่างMatches the screen to the family of the model it feeds, per the table below. | แล้วแต่ตระกูลDepends on the family |
| คัด collinearity (VIF > 10)Collinearity screen (VIF > 10) | ตัดตัวแปรที่ซ้ำซ้อนกันเชิงเส้นDrops predictors that duplicate each other. | ไม่เลย — จึงปลอดภัยไม่ว่าจะรันที่ขั้นตอนใดNever — so it is safe wherever it runs |
| คัดด้วย penalized regression (elastic net)Penalised screen (elastic net) | บทลงโทษบีบสัมประสิทธิ์ที่อ่อนให้เป็นศูนย์ เหมาะกับโมเดลตระกูลเชิงเส้นA penalised fit zeroes weak coefficients; family-matched to linear models. | ใช่ (ฟิตใหม่ในทุก fold)Yes (re-fitted per fold) |
| คัดด้วยความสำคัญจากโมเดล (random forest)Model importance screen (random forest) | ใช้ค่าความสำคัญจากป่าสุ่ม เก็บตัวแปรที่ค่าเกินค่ามัธยฐาน เหมาะกับโมเดลตระกูลต้นไม้Keeps predictors above the median random-forest importance; family-matched to tree models. | ใช่ (ฟิตใหม่ในทุก fold)Yes (re-fitted per fold) |
| คัด collinearity → คัดด้วย elastic netCollinearity screen → penalised screen | ตัดตัวซ้ำซ้อนก่อน แล้วจึงคัดด้วยบทลงโทษCollinearity screen first, then the penalised screen. | ใช่ (ขั้นที่สอง)Yes (second stage) |
ทำไมต้องจับคู่ตัวคัดกับตระกูลของโมเดล — นี่คือหลักการของ embedded methods (Guyon & Elisseeff 2003; Kuhn & Johnson 2013 บทที่ 19): ถ้าใช้ตัวคัดเชิงเส้นส่งตัวแปรที่รอดให้กับโมเดล boosted tree เท่ากับบังคับมุมมองเชิงเส้นใส่โมเดลที่ถูกเลือกมาเพราะมันไม่เป็นเชิงเส้น
Why the screen is family-matched — this is the embedded-methods principle (Guyon & Elisseeff 2003; Kuhn & Johnson 2013, ch. 19): a linear screen handing its survivors to a boosted-tree model imposes a linear view on a model chosen for not being linear.
| ตระกูลของโมเดลModel family | ตัวอย่างโมเดลExamples | ตัวคัดที่โหมด "อัตโนมัติ" เลือกให้Screen chosen by "Auto" |
|---|---|---|
| เชิงเส้นLinear | Logistic · Linear · Ridge · Lasso · Elastic Net · Linear SVM | คัดด้วย penalized regression (elastic net)penalised (elastic net) |
| ต้นไม้Tree | Decision Tree · Random Forest · Extra Trees · Gradient Boosting · XGBoost · LightGBM · CatBoost · AdaBoost | คัดด้วยความสำคัญจากโมเดล — ต้นไม้ทนต่อ collinearity อยู่แล้ว สิ่งที่ได้จากการคัดคือค่า SHAP ที่เสถียรขึ้นmodel importance — trees tolerate correlated predictors; the gain is stabler SHAP |
| Kernel / ระยะทางKernel / distance | SVM (RBF) · k-NN | คัด collinearity → elastic net (ระยะทางบิดเบือนเมื่อตัวแปรซ้ำซ้อน)collinearity → elastic net (duplicated predictors distort the distance) |
| โครงข่ายประสาทเทียมNeural network | Multi-layer Perceptron | คัด collinearitycollinearity |
| Naive Bayes | Gaussian NB | คัด collinearity — ความเป็นอิสระต่อกันคือข้อสมมติของโมเดลนี้เอง collinearity จึงละเมิดข้อสมมติโดยตรงcollinearity — independence is this model's own assumption, which collinearity violates directly |
เมื่อเปิดทั้ง Train/Test และ Cross-Validation พร้อมกัน — ใครเป็นผู้เลือก สองค่านี้วัดคนละอย่าง (CV = ทุกแถวในข้อมูลฝึก แบ่ง k รอบ · Test = ข้อมูลที่กันไว้ก้อนเดียวซึ่งแบบจำลองไม่เคยเห็น) การหยิบ "ค่าไหนสูงกว่าก็เอาอันนั้น" จึงเป็นการเลือกค่าสูงสุดจากประมาณค่าจำนวน 2 × จำนวนโมเดล ซึ่งลำเอียงขึ้นโดยโครงสร้าง และที่สำคัญกว่านั้น ถ้าข้อมูลทดสอบเป็นผู้เลือก ข้อมูลชุดนั้นก็ไม่ใช่ข้อมูลที่กันไว้อีกต่อไป ค่าที่รายงานว่าเป็นค่าประเมินอย่างไม่ลำเอียงจะกลายเป็นค่าที่ถูกทำให้สูงสุดเสียเอง
การแบ่งหน้าที่ตามมาตรฐาน (ESL §7.2; Kuhn & Johnson 2013; TRIPOD+AI 2024) คือ ให้การสุ่มซ้ำภายในข้อมูลฝึกเป็นผู้เลือก และให้ข้อมูลที่กันไว้เป็นผู้ประเมิน DAPH จึงใช้ค่า cross-validation คัดเลือกแบบจำลองที่ดีที่สุดเสมอเมื่อมีค่านั้น แล้วรายงานค่าจากข้อมูลทดสอบเป็นประสิทธิภาพของแบบจำลองที่เลือก โดยระบุไว้ในรายงานว่าใครเลือกและใครรายงาน หากไม่ได้เปิด cross-validation ข้อมูลทดสอบจะทำหน้าที่ทั้งสองอย่าง — ใช้ได้ แต่รายงานจะเขียนกำกับไว้ว่าค่าที่ได้ดีเกินจริงสำหรับแบบจำลองที่ถูกเลือก
When both Train/Test and Cross-Validation are enabled — which one chooses? The two measure different things (CV = every training row, k rounds; Test = one held-out block the model never saw). Taking "whichever number is higher" maximises over 2 × n_models estimates, which is biased upward by construction — and worse, if the test set does the choosing it is no longer held out: the number reported as the unbiased estimate is the very number that was maximised.
The standard division of labour (ESL §7.2; Kuhn & Johnson 2013; TRIPOD+AI 2024) is that resampling on the training data selects and the held-out set estimates. DAPH therefore always selects with the cross-validated metric when one exists and reports the test metric as the selected model's performance, stating in the report which did which. Without cross-validation the test set does both jobs — permitted, but the report says so explicitly.
3สคริปต์ R ที่เทียบเคียงกันEquivalent R Script
library(caret); library(glmnet); library(randomForest); library(car)
# WRONG — the screen sees every row, then folds are drawn afterwards
xs <- names(which(abs(cor(d[, xs], d$y)) > .3))
train(y ~ ., data = d[, c(xs, "y")], method = "glmnet",
trControl = trainControl(method = "cv", number = 5)) # optimistic
# RIGHT — the screen is re-fitted inside every resample
ctrl <- rfeControl(functions = rfFuncs, method = "cv", number = 5)
rfe(d[, xs], d$y, sizes = c(5, 10, 20), rfeControl = ctrl)
# the individual screens
car::vif(lm(y ~ ., data = d)) # collinearity
cv.glmnet(as.matrix(d[, xs]), d$y, alpha = .5) # elastic net
randomForest::importance(randomForest(y ~ ., data = d)) # importance
4การแปลผลและการรายงานInterpretation and Reporting
เพราะตัวคัดถูกฟิตใหม่ในทุก fold ชุดตัวแปรที่รอดจึงอาจไม่เหมือนกันในแต่ละ fold — นั่นไม่ใช่ข้อผิดพลาด แต่เป็นภาพสะท้อนความไม่แน่นอนของการคัดเลือกที่วิธีคัดครั้งเดียวซ่อนเอาไว้ ถ้าตัวแปรตัวหนึ่งรอดในบาง fold เท่านั้น แปลว่าหลักฐานสนับสนุนตัวแปรนั้นยังไม่หนักแน่น
ตามแนวปฏิบัติ TRIPOD+AI (2024) การรายงานแบบจำลองทำนายควรระบุ: จำนวนตัวแปรที่นำเข้าพิจารณา · วิธีคัดและจุดที่มันทำงานในสายการประมวลผล · วิธีแบ่งข้อมูลตรวจสอบ · และค่าประสิทธิภาพจากข้อมูลที่แบบจำลองไม่เคยเห็น พร้อมช่วงเชื่อมั่น
Because the selector is re-fitted per fold, the surviving set can differ between folds. That is not a defect — it is the selection uncertainty that a select-once workflow hides. A predictor surviving in only some folds has weak support.
Following TRIPOD+AI (2024), a prediction-model report should state: the number of candidate predictors, the screening method and where it sits in the pipeline, the validation scheme, and held-out performance with confidence intervals.
สำหรับข้อมูลเชิงพื้นที่และเชิงเวลา: การแบ่ง fold แบบสุ่มธรรมดาจะให้ค่าดีเกินจริงเมื่อพื้นที่ข้างเคียงคล้ายกัน (Roberts et al. 2017) DAPH จึงแบ่ง fold เป็นบล็อกเชิงพื้นที่สำหรับ Spatial ML และกันช่วงเวลาท้ายไว้ทดสอบตามลำดับเวลาสำหรับ Spatio-Temporal ML
For spatial and temporal data: plain random folds are optimistic when neighbouring areas resemble each other (Roberts et al. 2017), so DAPH uses spatial block folds for Spatial ML and holds out the last periods in time order for Spatio-Temporal ML.
📖 References
- Ambroise, C., & McLachlan, G. J. (2002). Selection bias in gene extraction on the basis of microarray gene-expression data. PNAS, 99(10), 6562–6566. doi:10.1073/pnas.102102699
- Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.), §7.10.2. New York: Springer. doi:10.1007/978-0-387-84858-7
- Guyon, I., & Elisseeff, A. (2003). An introduction to variable and feature selection. Journal of Machine Learning Research, 3, 1157–1182.
- Kuhn, M., & Johnson, K. (2013). Applied Predictive Modeling, ch. 19. New York: Springer. doi:10.1007/978-1-4614-6849-3
- Roberts, D. R., et al. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913–929. doi:10.1111/ecog.02881
- Collins, G. S., et al. (2024). TRIPOD+AI statement: updated guidance for reporting clinical prediction models that use regression or machine learning methods. BMJ, 385, e078378. doi:10.1136/bmj-2023-078378
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification
12.4การเลือกตัวแปรเข้าแบบจำลองสุดท้าย — Linear · Logistic · Poisson · CoxBuilding the Final Model — Linear · Logistic · Poisson · Cox
1บทนำและความสำคัญทางสาธารณสุขIntroduction and Public-Health Relevance
สถิติกลุ่มนี้ ไม่มีดรอปดาวน์คัดตัวแปรอัตโนมัติ — ผู้วิจัยเป็นผู้ตัดสินว่าตัวแปรใดอยู่ในแบบจำลองสุดท้าย ด้วยเหตุนี้ขั้นตอนการตัดสินจึงยิ่ง ต้อง เขียนให้ชัด เพราะไม่มีอัลกอริทึมใดมารับผิดชอบแทน และผู้อ่านรายงานต้องตรวจสอบเหตุผลได้
สิ่งสำคัญที่สุดที่ต้องเข้าใจก่อน: บทบาทของตัวแปรกำหนดชะตากรรมของมัน ไม่ใช่ค่า p ตัวแปรในแบบจำลองทางระบาดวิทยาแบ่งได้เป็นสี่บทบาท และแต่ละบทบาทมีกติกาคนละแบบ
- ตัวแปรหลักที่สนใจ (exposure) — อยู่ในแบบจำลองเสมอ ไม่ว่าจะมีนัยสำคัญหรือไม่
- ตัวแปรกวน (confounder) — เกี่ยวข้องกับทั้ง exposure และผลลัพธ์ และไม่ได้อยู่บนเส้นทางเชิงสาเหตุ ต้องคงไว้แม้ p สูง การตัดออกเพราะไม่มีนัยสำคัญคือการปล่อยให้อคติกลับเข้ามา
- ตัวแปรคั่นกลาง (mediator) — อยู่บนเส้นทางจาก exposure ไปผลลัพธ์ การใส่เข้าไปจะปิดกั้นผลรวมที่ต้องการวัด ถ้าสนใจผลรวม ต้องไม่ใส่
- ตัวแปรร่วมทำนาย (precision variable) — สัมพันธ์กับผลลัพธ์แต่ไม่สัมพันธ์กับ exposure ใส่แล้วช่วยให้ช่วงเชื่อมั่นแคบลง
- The exposure of interest — always in the model, significant or not.
- Confounders — associated with both the exposure and the outcome and not on the causal path; keep them regardless of p. Dropping a confounder for being non-significant simply lets the bias back in.
- Mediators — on the path from exposure to outcome; including one blocks the total effect you set out to measure.
- Precision variables — related to the outcome but not to the exposure; including them narrows the confidence intervals.
These statistics deliberately have no automated selection dropdown — the researcher decides what enters the final model. That makes documenting the procedure more important, not less: no algorithm carries the responsibility, and the reader must be able to audit the reasoning.
The key idea comes first: a variable's role decides its fate, not its p-value.
2ขั้นตอนที่ใช้กันเป็นมาตรฐานThe Standard Procedures
(ก) Purposeful selection (Hosmer, Lemeshow & Sturdivant 2013) — แนวทางที่นิยมที่สุดในงานระบาดวิทยา เพราะรวมทั้งค่า p และการเปลี่ยนแปลงของค่าประมาณไว้ด้วยกัน
(a) Purposeful selection (Hosmer, Lemeshow & Sturdivant 2013) — the most common epidemiological workflow, because it uses both p-values and change-in-estimate.
| ขั้นStep | ทำอะไรWhat to do | เหตุผลWhy |
|---|---|---|
| 1 | วิเคราะห์ทีละตัวแปร (univariable) แล้วคัดตัวที่ p < 0.20–0.25 เข้าสู่รอบถัดไปRun univariable analyses and carry forward those with p < 0.20–0.25. | เกณฑ์ 0.05 ตั้งแต่รอบแรกจะตัดตัวแปรที่มีผลเฉพาะเมื่อควบคุมตัวอื่นทิ้งไปA 0.05 cut at this stage discards variables that matter only once others are controlled. |
| 2 | ใส่ทั้งหมดเข้าแบบจำลองพหุตัวแปร แล้วทยอยตัดตัวที่ไม่มีนัยสำคัญทีละตัวFit the multivariable model, then remove non-significant terms one at a time. | ตัดทีละตัวเพราะการตัดหนึ่งตัวเปลี่ยนค่าของตัวที่เหลือOne at a time, because each removal changes the remaining estimates. |
| 3 | ตรวจ change-in-estimate: ถ้าการตัดตัวแปรใดทำให้ค่าสัมประสิทธิ์ของตัวแปรที่เหลือเปลี่ยนเกิน 10% ให้ ใส่กลับ แม้ p จะไม่มีนัยสำคัญChange-in-estimate check: if removing a variable shifts a remaining coefficient by more than 10%, put it back even though p is non-significant. | นี่คือการตรวจจับตัวแปรกวนตัวจริง — เป็นขั้นที่ถูกข้ามบ่อยที่สุดThis is what actually detects confounding — and the step most often skipped. |
| 4 | นำตัวแปรที่ตกรอบแรกกลับมาลองใส่อีกครั้งทีละตัวRe-offer the variables excluded at step 1, one at a time. | บางตัวมีผลเฉพาะเมื่อมีตัวแปรอื่นอยู่ในแบบจำลองแล้วSome only matter in the presence of the others. |
| 5 | ตรวจรูปแบบความสัมพันธ์ (linearity) และปฏิสัมพันธ์ (interaction) ที่ตั้งสมมติฐานไว้ล่วงหน้าCheck functional form (linearity) and any pre-specified interactions. | ปฏิสัมพันธ์ที่ไม่ได้ตั้งไว้ล่วงหน้าคือการค้นหาโดยข้อมูล ต้องรายงานว่าเป็นการสำรวจUnplanned interactions are data-driven and must be reported as exploratory. |
(ข) แบบตั้งไว้ล่วงหน้าทั้งหมด (pre-specified) — กำหนดชุดตัวแปรจากทฤษฎีและงานวิจัยก่อนหน้า แล้วรายงานแบบจำลองนั้นชุดเดียว ไม่มีการค้นหา วิธีนี้ให้ค่า p และช่วงเชื่อมั่นที่ตีความได้ตรงตามนิยาม และเป็นวิธีที่ Harrell (2015) แนะนำเมื่อจำนวนตัวอย่างเพียงพอ
(b) Fully pre-specified — fix the covariate set from theory and prior work, fit it once, report it. No search means the p-values and intervals mean what they claim; Harrell (2015) recommends this whenever the sample supports it.
(ค) แบบมีบทลงโทษ (penalized) — เมื่อตัวแปรมากเมื่อเทียบกับจำนวนตัวอย่าง วิธีที่มีบทลงโทษออกแบบมาสำหรับสถานการณ์นี้โดยตรง และไม่มีปัญหาอคติแบบ stepwise
(c) Penalised — when the candidate set is large relative to n, penalised methods are built for exactly this and avoid the stepwise bias.
3ข้อควรระวังเฉพาะของแต่ละสถิติ และสคริปต์ RStatistic-Specific Cautions and R Script
| สถิติStatistic | ข้อจำกัดด้านขนาดตัวอย่างSample-size constraint | สิ่งที่ต้องตรวจเพิ่มExtra checks |
|---|---|---|
| Linear regressionLinear regression | ~10–15 แถวต่อพารามิเตอร์~10–15 rows per parameter | ความเป็นเชิงเส้น · ความแปรปรวนคงที่ · การแจกแจงของส่วนเหลือ · VIFlinearity · homoscedasticity · residual distribution · VIF |
| Logistic regressionLogistic regression | ~10 เหตุการณ์ ต่อตัวแปร (นับกลุ่มที่น้อยกว่า)~10 events per variable (count the smaller class) | ความเป็นเชิงเส้นของตัวแปรต่อเนื่องกับ logit · การแยกสมบูรณ์ (separation) · Hosmer–Lemeshowlinearity in the logit · complete separation · Hosmer–Lemeshow |
| Poisson regressionPoisson regression | ~10 เหตุการณ์ต่อตัวแปร~10 events per variable | overdispersion (ถ้าความแปรปรวน > ค่าเฉลี่ย ต้องใช้แบบ negative binomial) · offset ของเวลาหรือประชากรเสี่ยง ต้องใส่เสมอเมื่อรายงานเป็นอัตราoverdispersion (variance > mean calls for negative binomial) · an offset for person-time or population at risk whenever a rate is reported |
| Cox regressionCox regression | ~10 เหตุการณ์ต่อตัวแปร — นับ จำนวนเหตุการณ์ ไม่ใช่จำนวนคน~10 events per variable — count events, not people | สมมติฐาน proportional hazards (ตรวจด้วย Schoenfeld residuals) ถ้าละเมิด ให้ใช้ตัวแปรที่ขึ้นกับเวลาหรือแบ่งชั้น (stratify)proportional hazards (Schoenfeld residuals); if violated, use a time-varying term or stratify |
# change-in-estimate: does dropping the covariate move the exposure effect?
full <- glm(y ~ exposure + age + sex + income, family = binomial, data = d)
red <- glm(y ~ exposure + sex + income, family = binomial, data = d)
100 * (coef(red)["exposure"] - coef(full)["exposure"]) / coef(full)["exposure"]
# |change| > 10% -> age is a confounder: keep it, whatever its p-value
# model comparison by likelihood ratio (nested models only)
anova(red, full, test = "LRT")
AIC(full, red)
# statistic-specific checks
performance::check_overdispersion(glm(cases ~ x + offset(log(pop)),
family = poisson, data = d))
cox.zph(coxph(Surv(time, event) ~ x + age, data = d)) # proportional hazards
generalhoslem::logitgof(d$y, fitted(full)) # Hosmer-Lemeshow
4การรายงานในบทความReporting in a Manuscript
ตามแนวปฏิบัติ STROBE (von Elm et al. 2007) ข้อ 12(a) หัวข้อระเบียบวิธีต้องระบุ "ตัวแปรใดถูกนำเข้าแบบจำลอง และเพราะเหตุใด" ให้เขียนครบสี่อย่าง: (1) ชุดตัวแปรที่พิจารณาทั้งหมด · (2) เกณฑ์ที่ใช้คัดเข้า/ออก (เช่น univariable p < 0.20 และ change-in-estimate 10%) · (3) ตัวแปรที่คงไว้เพราะเป็นตัวแปรกวนแม้ไม่มีนัยสำคัญ · (4) ปฏิสัมพันธ์ที่ตรวจสอบ และตั้งไว้ล่วงหน้าหรือไม่
STROBE item 12(a) (von Elm et al. 2007) asks the methods section to state which variables entered the model and why. Report all four: (1) the full candidate set, (2) the entry/exit criteria (e.g. univariable p < 0.20 plus a 10% change-in-estimate rule), (3) variables kept as confounders despite non-significance, and (4) which interactions were examined and whether they were pre-specified.
ประโยคตัวอย่างที่ใช้ได้จริง: "นำตัวแปรที่มี p < 0.20 จากการวิเคราะห์ทีละตัวแปรเข้าสู่แบบจำลองพหุตัวแปร จากนั้นตัดตัวแปรที่ไม่มีนัยสำคัญออกทีละตัว โดยคงตัวแปรที่การตัดออกทำให้ค่าสัมประสิทธิ์ของตัวแปรหลักเปลี่ยนแปลงเกินร้อยละ 10 ไว้ในแบบจำลอง และคงอายุกับเพศไว้ตลอดในฐานะตัวแปรควบคุมที่กำหนดไว้ล่วงหน้า"
A sentence that works: "Variables with p < 0.20 in univariable analysis entered the multivariable model; non-significant terms were removed one at a time, retaining any whose removal changed the exposure coefficient by more than 10%. Age and sex were retained a priori."
📖 References
- Hosmer, D. W., Lemeshow, S., & Sturdivant, R. X. (2013). Applied Logistic Regression (3rd ed.). Hoboken: Wiley. doi:10.1002/9781118548387
- Harrell, F. E. (2015). Regression Modeling Strategies (2nd ed.), §4.3. Cham: Springer. doi:10.1007/978-3-319-19425-7
- Greenland, S. (1989). Modeling and variable selection in epidemiologic analysis. American Journal of Public Health, 79(3), 340–349. doi:10.2105/AJPH.79.3.340
- Maldonado, G., & Greenland, S. (1993). Simulation study of confounder-selection strategies. American Journal of Epidemiology, 138(11), 923–936. doi:10.1093/oxfordjournals.aje.a116813
- Peduzzi, P., Concato, J., Kemper, E., Holford, T. R., & Feinstein, A. R. (1996). A simulation study of the number of events per variable in logistic regression analysis. Journal of Clinical Epidemiology, 49(12), 1373–1379. doi:10.1016/S0895-4356(96)00236-3
- Grambsch, P. M., & Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. Biometrika, 81(3), 515–526. doi:10.1093/biomet/81.3.515
- von Elm, E., Altman, D. G., Egger, M., Pocock, S. J., Gøtzsche, P. C., & Vandenbroucke, J. P. (2007). The Strengthening the Reporting of Observational Studies in Epidemiology (STROBE) statement. The Lancet, 370(9596), 1453–1457. doi:10.1016/S0140-6736(07)61602-X
- Sornlorm, K. (2026). DAPH Guide: Statistical methods in DAPH (Data Analysis for Public health Research). Retrieved from https://innovageotech.com/statistics-verification