Understanding Statistical Models

A practical path from group comparisons to mixed-effects models

Dr. Jun Ho Chai

Children’s Preference for Child-Directed Speech

아동은 아동지향어(CDS)를 더 오래 들을까요?

Each child hears both child-directed speech (CDS; 아동지향어) and adult-directed speech (ADS; 성인지향어). We record how long the child listens to each one.

CDS preference score · CDS 선호 점수 = listening time to CDS − listening time to ADS

What Could Explain the Variation?

관측된 차이는 어디에서 올까요?
Child characteristic 아동 특성
age · 나이
Demographic variable: measure it, but cannot control it측정 가능, 통제 불가
Study design choices 연구 설계 선택
novelty-preference task
habituation task
recognition task
Can control through study design연구 설계로 통제 가능
Remaining variation 남은 변동
momentary attention · fatigue or fussiness · measurement noise
Cannot fully control; can minimize완전한 통제는 어렵지만 최소화 가능
may contribute to
Observed CDS preference score 관측된 CDS 선호 점수
listening time to CDS − listening time to ADS

Roadmap

오늘의 진행 순서
Part Main focus Units
1. Comparing conditions조건 비교 Mean differences, 0/1 coding, and comparisons among several groups 1–3
2. Modelling relationships관계 모형화 Continuous predictors and adjustment for other variables 4–5
3. Conditional effects조건부 효과 Whether an association changes with another predictor 6
4. Matching the data structure자료 구조에 맞추기 Binary and count outcomes; repeated observations 7–8

Unit 1 — Comparing Two Groups

Compare two condition means while accounting for variation within each condition.
group (집단) · mean (평균) · mean difference (평균 차이) · variation (변동) · standard error (표준오차) · t statistic (t값)

A Two-Condition Learning Study

Condition 1 · spoken label only
Study situation
A caregiver labels a target object for a child using speech alone.
Input
“Look, this is the target object.”
Condition 2 · spoken label + pointing gesture
Study situation
The same spoken label is used, but the caregiver also points to the target.
Input
“Look, this is the target object.” + pointing

Outcome: child word-learning score

The conditions differ only in whether the spoken label is accompanied by a pointing gesture.

Raw Scores in the Two Conditions

We can begin by comparing the scores in the two conditions.

Point · observed value (관측값)x-axis · group (집단)y-axis · outcome (결과변수)

Group Means

Mean · 평균
A single value that summarizes the observations in each group.
Thick black line · group mean (집단 평균)Point · observed value (관측값)

Between-Group Difference

Mean difference · 평균 차이
The vertical difference between the two group means.
Black line · group mean (집단 평균)Vertical difference · mean difference (평균 차이)

Within-Group Variation

Within-group variation · 집단 내 변동
How far observations within a group lie from their group mean.
Vertical distance · observation minus group mean (관측값 − 집단 평균)Black line · group mean (집단 평균)

Uncertainty in the Mean Difference

Standard error · 표준오차 — how much an estimate can vary across samples.
Confidence interval · 신뢰구간 — a range showing uncertainty in the estimated mean difference.
Orange point · estimate (추정값)Orange line · 95% confidence interval (신뢰구간)

The t Statistic

t statistic · t값
The estimated mean difference divided by its standard error.

Interactive Two-Group Comparison

1 · Look보세요points and group means
2 · Compare비교해 보세요mean difference and within-group variation
3 · Change바꿔 보세요mean difference, SD, and sample size
4 · Check확인해 보세요t, p, and the confidence interval

Try changing one setting at a time: - mean difference - within-group SD - sample size

R
t.test(word_learning ~ condition, data = children)

Point · observed value (관측값)Thick black line · group mean (집단 평균)Orange point and line · estimate and 95% confidence interval (추정값·신뢰구간)

Unit 2 — Two Groups as a Linear Model

Represent two conditions with 0/1 coding and express their mean difference as a model coefficient.
predictor (예측변수) · intercept (절편) · slope (기울기) · coefficient (계수) · fitted value (적합값) · residual (잔차)

Representing the Two Conditions with a Predictor

Condition
Code X
Mean score
Spoken label only
0
50.25
Speech + gesture
1
56.00
In Unit 1, we compared the two means directly.
Unit 2 represents the same two conditions numerically as X = 0 and X = 1.

Coding the Two Conditions as 0 and 1

The same scores and group means are shown after recoding the condition variable.

Spoken label only: X = 0
Speech + gesture: X = 1
Predictor · 예측변수
A variable used to explain differences or changes in the outcome. Here, the two conditions are coded X = 0 and X = 1.

The Intercept

Intercept (β₀) · 절편
The fitted value when X = 0.

\[ \beta_0 = \operatorname{E}(Y \mid X = 0) \]

The Fitted Line

Fitted line · 적합선
The line connecting the model’s fitted values at X = 0 and X = 1.
Black line · fitted line (적합선)Black point · fitted value (적합값)Blue point · observed value (관측값)

The Coefficient as the Change from 0 to 1

slope β₁ (기울기) = change in fitted value ÷ change in X = (56.00 − 50.25) ÷ (1 − 0) = 5.75

Coefficient · 계수
In this 0/1 model, β₁ is the change in the fitted value from X = 0 to X = 1, equal to the difference between the group means.

Residual Distance from the Fitted Line

residual eᵢ (잔차) = observed value Yᵢ − fitted value Ŷᵢ

Residual · 잔차
The vertical distance between an observed value and the fitted line: observed value − fitted value.
Orange point · observed value (관측값)Black point · fitted value (적합값)Orange vertical distance · residual (잔차)

Components of the Two-Group Linear Model

Yᵢ = β₀ + β₁Xᵢ + eᵢ

β₀ · intercept (절편) · fitted value at X = 0 β₁ · slope (기울기) · change from X = 0 to X = 1 eᵢ · residual (잔차) · vertical distance

Residual Variation Limits Exact Prediction

\[Y_i=\widehat{Y}_i+e_i\]

The fitted line gives the model’s best estimate of the expected score. Because individual observations still contain residual variation, the exact value of a new \(Y_i\) cannot be known from condition alone.

Blue band · fitted line ± residual SD (적합선 ± 잔차 SD)Black line · fitted line (적합선)Point · observed value (관측값)

Model Predictions for X = 0 and X = 1

X = 0 · Spoken label only

Ŷ = β₀ + β₁(0) = β₀

Fitted mean = 50.25

X = 1 · Speech + gesture

Ŷ = β₀ + β₁(1) = β₀ + β₁

Fitted mean = 56.00

Under 0/1 coding, the intercept and slope reproduce the two fitted group means.

Equivalence of the t-Test and the Linear-Model Coefficient

Unit 1
Mean difference
Ȳ₁ − Ȳ₀
=
Unit 2
Slope for the 0/1 predictor
β̂₁

\[ t = \frac{\text{mean difference}}{\operatorname{SE}(\text{mean difference})} = \frac{\widehat{\beta}_1}{\operatorname{SE}(\widehat{\beta}_1)} \]

t.test(word_learning ~ condition, var.equal = TRUE)
lm(word_learning ~ condition)

For independent groups, the pooled-variance t-test and the 0/1 linear model use the same estimated difference and standard error.

Interactive Reference-Group Coding

1 · Look보세요the two fitted values and black line
2 · Compare비교해 보세요the positions of 0 and 1
3 · Change바꿔 보세요the reference group
4 · Check확인해 보세요the intercept, slope, and p-value

Unit 3 — Comparing Several Groups

Compare three or more means by relating between-group variation to within-group variation.
between-group variation (집단 사이 변동) · within-group variation (집단 내 변동) · F statistic (F값) · reference group (기준집단) · indicator variable (지시변수)

Three Conditions

With three conditions, there is more than one possible comparison between means:

ANOVA summarizes the picture by comparing two kinds of variation:

\[F=\frac{\text{between-group variation}}{\text{within-group variation}}\]

F statistic · F값
Between-group variation divided by within-group variation.
Thick black line · group mean (집단 평균)Point · observed value (관측값)

Between-Group Variation

Between-group variation · 집단 사이 변동
How far the group means lie from the grand mean. This is the numerator of F.
Dashed line · grand mean (전체 평균)Thick line · group mean (집단 평균)Vertical distance · between-group variation (집단 사이 변동)

Within-Group Variation

Within-group variation · 집단 내 변동
How far individual observations lie from their own group mean. This is the denominator of F.
Vertical distance · within-group variation (집단 내 변동)Thick line · group mean (집단 평균)Point · observed value (관측값)

Interactive Group Means and Within-Group Spread

1 · Look보세요the three group means
2 · Compare비교해 보세요between- and within-group variation
3 · Change바꿔 보세요means, SD, and sample size
4 · Check확인해 보세요F, p, and the coefficients

F = between-group variation within-group variation

R:
model <- lm(word_learning ~ condition, data = children)
anova(model)

Dashed line · specified group mean (설정한 집단 평균)Thick line · sample mean (표본 평균)Point · observed value (관측값)

Try the Three-Condition Prediction

1 · Look보세요the reference group and model equation
2 · Compare비교해 보세요the two indicator variables
3 · Change바꿔 보세요X₁, X₂, and the predicted value
4 · Check확인해 보세요your entered answer

With Speech only as the reference, \(X_1=1\) indicates Speech + gesture and \(X_2=1\) indicates Gesture only.

Reference group · 기준집단 — the group used as the comparison point. Indicator variable · 지시변수 — coded 1 for that group and 0 otherwise.

\[ \widehat{Y}_i = 50 + 6X_{1i} - 2X_{2i} \]

Unit 4 — Continuous Predictors and Linear Regression

Locate slope, residuals, and uncertainty when the predictor can take many numerical values.
continuous predictor (연속형 예측변수) · regression line (회귀선) · slope (기울기) · residual (잔차) · confidence interval (신뢰구간)

A Continuous Predictor

Conversational turns can be analysed as a continuous measure rather than divided into “low” and “high” groups.

Continuous predictor · 연속형 예측변수
A predictor that can take many numerical values. The expected change in the outcome for a one-unit increase in X is the slope.
Point · observed value (관측값)Black line · regression line (회귀선)x-axis · predictor (예측변수)y-axis · outcome (결과변수)

Slope on the Fitted Line

Slope · 기울기
The expected change in Y for a one-unit increase in X: rise ÷ run.
Horizontal arrow · change in X (X의 변화) (run)Vertical arrow · change in fitted value (적합값의 변화) (rise)Black line · regression line (회귀선)

Residuals on the Fitted Line

Residual · 잔차
The vertical distance between an observed value and the fitted line: observed value − fitted value.
Orange point · observed value (관측값)Orange vertical arrow · residual (잔차)Black line · fitted line (적합선)

Uncertainty Around the Fitted Line

Confidence interval · 신뢰구간
A range showing uncertainty in the estimated mean. It is narrower near the centre and wider toward the ends.
Blue band · 95% confidence interval for the mean (신뢰구간)Black line · fitted line (적합선)Point · observed value (관측값)

Interactive Slope, Residuals, and Precision

1 · Change바꿔 보세요the slope
2 · Compare비교해 보세요the distances between points and line
3 · Increase늘려 보세요the sample size
4 · Check확인해 보세요the confidence interval and p-value

Try the controls in this order: slope → residual SD → sample size.

R:
model <- lm(vocabulary ~ turns, data = children)
confint(model)

Point · observed value (관측값)Vertical distance · residual (잔차)Orange line · fitted line (적합선)Blue band · 95% confidence interval (신뢰구간)

Unit 5 — Adjustment and Multiple Regression

Compare the raw association with the association estimated while another predictor is held constant.
raw association (원자료 관계) · adjusted association (조정된 관계) · hold constant (통제하다) · coefficient (계수) · multiple regression (다중회귀)

Age Adjustment in a Scatterplot

Suppose that older children tend to have more conversational turns and higher language scores.

The overall upward pattern reflects differences in both conversational turns and age.

Adjusted question: Among children of similar age, are more conversational turns associated with higher language scores?

Adjustment · 조정
Estimate the association between conversational turns and language score while comparing children of similar age.
Point · observed value (관측값)Black line · raw association (원자료 관계)Point colour · age (나이)

Reading the Scatterplot Before the Model

The scatterplot contains two related patterns:

  • older children tend to be further to the upper-right;
  • within an age band, children can still differ in turns.

The adjusted coefficient estimates the turns–language association after accounting for the age pattern.

Raw association · 원자료 관계 — the overall relationship without adjusting for age.
Adjusted association · 조정된 관계 — the relationship among children of similar age.

Adjusted Coefficients in a Scatterplot

\[Y_i=\beta_0+\beta_1\mathrm{Turns}_i+\beta_2\mathrm{Age}_i+\varepsilon_i\]

  • \(\beta_1\): association between turns and language holding age constant;
  • \(\beta_2\): association between age and language holding turns constant.
Hold constant · 통제하다
Interpret one coefficient while another predictor is kept at the same value. This does not by itself imply a causal effect.

The raw and adjusted coefficients may differ because age is related to both the predictor and the outcome.

Raw coefficient
overall turns–language association
Adjusted coefficient
turns–language association at similar age

Interactive Raw and Adjusted Associations

1 · Look보세요point colour and the raw line
2 · Compare비교해 보세요raw and adjusted coefficients
3 · Change바꿔 보세요the age effect and correlation
4 · Check확인해 보세요both coefficients and p-values

First set the turns effect to 0; then increase the age effect and the age–turn correlation.

R:
lm(language ~ turns + age, data = children)

Black line · raw association (원자료 관계)Green bar · adjusted coefficient (조정 계수)Grey bars · raw and specified coefficients (원자료·설정 계수)Point colour · age (나이)

Unit 6 — Interaction and Conditional Effects

Examine whether the association with one predictor changes across values of another predictor.
main effect (주효과) · simple effect (단순효과) · simple slope (단순기울기) · interaction (상호작용) · centred age (중심화된 나이)

Interaction in a Two-by-Two Example

The size of the condition difference may vary by age group:

What is different?
First compare the vertical gap between conditions for younger and older children.
Interaction · 상호작용 — the condition effect differs by age group: 8 points for younger children and 16 points for older children.
Vertical gap · simple effect of condition (단순효과)Lines · fitted values by condition (조건별 적합값)

Main Effects, Simple Effects, and Interaction

Interactive Simple Slopes with Continuous Age

1 · Look보세요the fitted lines at three ages
2 · Compare비교해 보세요the three simple slopes
3 · Change바꿔 보세요the interaction coefficient
4 · Check확인해 보세요the slopes and p-values

Age is now treated as continuous. The interaction allows the turns slope to vary with age:

\[Y_i=\beta_0+\beta_1\mathrm{Turns}_i+\beta_2\mathrm{Age}_i+\beta_3(\mathrm{Turns}_i\times\mathrm{Age}_i)+\varepsilon_i\]

Begin with \(\beta_3=0\), and then try positive and negative values.

R:
lm(language ~ turns * age, data = children)

Point · observed value (관측값)Coloured lines · fitted lines by age (연령별 적합선)Line slope · simple slope (단순기울기)

Unit 7 — Generalized Linear Models

Match the model’s prediction scale to a continuous, binary, or count outcome.
binary outcome (이진 결과변수) · count outcome (횟수 결과변수) · probability (확률) · expected count (기대 횟수) · binomial distribution (이항분포) · Poisson distribution (포아송분포)

Valid Predictions for Different Outcomes

The form of a model should match the values that are possible for the outcome.

Outcome · 결과변수The variable being explained or predicted.
Continuous outcome · 연속형 결과변수
20   —   50   —   80
Predictions may take a wide range of numerical values.
Binary outcome · 이진 결과변수

✕ −0.2 ✓ 0 ✓ 1 ✕ 1.3

Predicted probability must stay between 0 and 1.
Count outcome · 횟수 결과변수

✕ −4 ✓ 0 ✓ 1 ✓ 2 ✓ 3…

Expected counts cannot be negative.

Before choosing a model, consider which values are possible for the outcome.

Linear Predictor and Prediction Scale

The systematic part remains:

\[ \eta = \beta_0 + \beta_1X \]

Linear predictor · 선형예측값A combination of coefficients and predictors, mapped to a scale appropriate for the outcome.
Continuous outcome · 연속형 결과변수
The linear predictor gives an expected score.

lm()

Binary outcome · 이진 결과변수
The linear predictor is transformed to a probability between 0 and 1.

glm(…, family = binomial)

Count outcome · 횟수 결과변수
The linear predictor is transformed to a positive expected count.

glm(…, family = poisson)

A generalized linear model maps the linear predictor onto the appropriate outcome scale.

Predicted Recognition Probability from a Logistic Model

Question: Does greater caregiver-response exposure predict whether a child recognizes a word?

\[X \longrightarrow \eta \longrightarrow P(\text{recognized})\]

  • \(\beta_1>0\): predicted probability tends to increase with \(X\).
  • \(\beta_1<0\): predicted probability tends to decrease with \(X\).

R
glm(recognized ~ exposure, family = binomial)

Binomial distribution · 이항분포The possible numbers of successes and their probabilities across a fixed number of trials.
Black curve · predicted probability (예측확률)Blue bars · binomial distribution (이항분포)Vertical dashed line · X = 3

Expected Vocalization Count from a Poisson Model

Question: Does caregiver responsiveness predict the number of child vocalizations?

\[X \longrightarrow \eta \longrightarrow E[Y]\]

  • \(\beta_1>0\): expected counts tend to increase with \(X\).
  • \(\beta_1<0\): expected counts tend to decrease with \(X\).

R
glm(vocalizations ~ responsiveness, family = poisson)

Poisson distribution · 포아송분포The possible counts and their probabilities within a fixed interval.
Black curve · expected count (기대 횟수)Orange bars · Poisson distribution (포아송분포)Vertical dashed line · X = 3

Interactive Logistic Prediction

1 · Look보세요the probability curve and binomial distribution
2 · Compare비교해 보세요probabilities at X = 1 and X = 4
3 · Change바꿔 보세요intercept, slope, and sample size
4 · Check확인해 보세요predicted probabilities and p-value

Change the slope first, then the number of children.

R:
glm(recognized ~ exposure, family = binomial)

Blue point · observed value (관측값)Orange curve · fitted probability (적합확률)Blue bars · binomial distribution (이항분포)

Interactive Poisson Prediction

1 · Look보세요the expected-count curve and Poisson distribution
2 · Compare비교해 보세요expected counts at X = 1 and X = 4
3 · Change바꿔 보세요intercept, slope, and sample size
4 · Check확인해 보세요expected counts and p-value

Change the slope first, then the number of children.

R:
glm(vocalizations ~ responsiveness, family = poisson)

Blue points · observed counts (관측 횟수)Orange curve · expected count (기대 횟수)Orange bars · Poisson distribution (포아송분포)

Unit 8 — Repeated Observations and Mixed Effects

Separate variation between children from variation among repeated observations within each child.
repeated observations (반복측정) · between-child variation (아동 사이 변동) · within-child variation (아동 내 변동) · random intercept (임의 절편) · mixed-effects model (혼합효과모형)

Repeated Observations from the Same Child

Measuring three children at four visits produces 12 rows from only 3 participants:

Repeated observations · 반복측정Two or more measurements from the same participant.

The four observations from Child B are related because they come from the same child.

Point · observation at each visit (방문별 관측값)Connecting line · change within child (아동 내 변화)x-axis · visit (방문)y-axis · outcome (결과변수)

Between-Child and Within-Child Variation

With repeated observations, the remaining variation can be separated into two sources:

Source Meaning Model term
Between-child variation · 아동 사이 변동 some children tend to be higher or lower overall child-specific random intercept \(u_{0j}\)
Within-child variation · 아동 내 변동 a visit can be above or below that child’s typical trajectory residual \(\varepsilon_{ij}\)

The model becomes:

$$ Y_{ij} = _0

1{ij}

u_{0j}

_{ij} $$

Observations from the same child share \(u_{0j}\) and are therefore not independent.

Random intercept · 임의 절편A term representing each child’s general tendency to score higher or lower.

Interactive: Within- and Between-Child Variation

1 · Look보세요each child’s points and line
2 · Compare비교해 보세요between- and within-child variation
3 · Change바꿔 보세요SD, children, and visits
4 · Check확인해 보세요the slope and p-value

Change between-child and within-child SD separately.

R:
lmer(language ~ age + (1 | child))

Blue lines · child trajectories (아동별 궤적)Black line · population fitted line (전체 적합선)x-axis · age (나이)y-axis · outcome (결과변수)

Putting the Models Together

Choose a model by checking the outcome, the predictor structure, and dependence among observations.
outcome (결과변수) · predictor (예측변수) · repeated observations (반복측정) · model choice (모형 선택)

Choosing a Model from the Outcome and Study Structure

What is the outcome?
Binary
Logistic regression
glm(…, family = binomial)
Continuous
Repeated or clustered rows?
Yes
Mixed-effects linear model
lmer(… + (1 | id))
No → predictor / research question
2 groups
two-group LM / t-test
lm() or t.test()
3+ groups
ANOVA / categorical LM
lm() + anova()
Continuous X
linear regression
lm()
Several X
multiple regression
lm()
Effect changes with another X
interaction / moderation
lm(y ~ x * z)
Count
Poisson regression
glm(…, family = poisson)
Choose the model in this order: outcome type → dependence among observations → predictor structure and research question.

Practice: Choose the Model

1 · Look보세요the study description
2 · Compare비교해 보세요outcome and predictors
3 · Change바꿔 보세요your A–D selections
4 · Check확인해 보세요the result after pressing Check

Thank You

Bonus Content

Actual R output from a reproducible simulated child-listening dataset

Estimate · 추정값Std. Error · 표준오차t value = Estimate ÷ Std. ErrorPr(>|t|) = p-value · p값
Read Estimate first, then check the p-value.

Simple Regression and the t-Test

Read Estimate first, then compare the t value and p-value.

Default R printing

old_options <- options(scipen = 0)
print(coef(summary(m_simple)))
             Estimate Std. Error   t value      Pr(>|t|)
(Intercept)  6.069693  0.1012051 59.974167 5.361379e-120
conditionCDS 1.073870  0.1431257  7.502985  2.863859e-12
options(old_options)

With options(scipen = 999)

old_options <- options(scipen = 999)
print(coef(summary(m_simple)))
             Estimate Std. Error   t value
(Intercept)  6.069693  0.1012051 59.974167
conditionCDS 1.073870  0.1431257  7.502985
                                                                                                                                     Pr(>|t|)
(Intercept)  0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005361379
conditionCDS 0.000000000002863859093720032028596354734354003214805151067423594213323667645454406738281250000000000000000000000000000000000000
options(old_options)
rbind(
  regression = c(
    estimate = unname(coef(m_simple)["conditionCDS"]),
    t = unname(coef(summary(m_simple))["conditionCDS", "t value"]),
    p = unname(coef(summary(m_simple))["conditionCDS", "Pr(>|t|)"])
  ),
  t_test = c(
    estimate = unname(diff(rev(tt$estimate))),
    t = unname(tt$statistic),
    p = tt$p.value
  )
)
           estimate        t            p
regression  1.07387 7.502985 2.863859e-12
t_test      1.07387 7.502985 2.863859e-12

scipen changes how small numbers are printed; it does not change the coefficient, t statistic, or p value. The final table also shows the regression–t-test equivalence.

Multiple Regression and ANOVA

Read each coefficient estimate, then check the ANOVA term and p-value.

Coefficient tests

m_multiple <- lm(
  looking_time ~ condition + age_c + task,
  data = cds_demo
)

printCoefmat(
  coef(summary(m_multiple)),
  digits = 3,
  signif.stars = FALSE
)
                Estimate Std. Error t value Pr(>|t|)
(Intercept)       6.0217     0.1105   54.47  < 2e-16
conditionCDS      1.0739     0.1105    9.71  < 2e-16
age_c             0.5053     0.0577    8.75  1.7e-15
taskHabituation  -0.3892     0.1354   -2.87  0.00455
taskRecognition   0.5333     0.1354    3.94  0.00012

Term-level ANOVA

anova(m_multiple)
Analysis of Variance Table

Response: looking_time
           Df Sum Sq Mean Sq F value    Pr(>F)    
condition   1 51.894  51.894  94.374 < 2.2e-16 ***
age_c       1 42.122  42.122  76.603 1.721e-15 ***
task        2 25.735  12.868  23.401 9.859e-10 ***
Residuals 175 96.228   0.550                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Read the coefficient rows as comparisons with reference levels. Read the ANOVA row for task as one joint test of its two coefficients.

Adding an Interaction

Read the interaction estimates, then check the age_c:task p-value in the ANOVA table.

Interaction coefficients

m_interaction <- lm(
  looking_time ~ condition + age_c * task,
  data = cds_demo
)

interaction_rows <- grep(
  "age_c:task",
  rownames(coef(summary(m_interaction)))
)

printCoefmat(
  coef(summary(m_interaction))[
    interaction_rows, , drop = FALSE
  ],
  digits = 3,
  signif.stars = FALSE
)
                      Estimate Std. Error t value Pr(>|t|)
age_c:taskHabituation    0.495      0.132    3.75  0.00024
age_c:taskRecognition   -0.173      0.132   -1.31  0.19203

ANOVA test of the interaction

anova(m_interaction)[
  c("age_c", "task", "age_c:task"),
]
Analysis of Variance Table

Response: looking_time
           Df Sum Sq Mean Sq F value    Pr(>F)    
age_c       1 42.122  42.122  87.799 < 2.2e-16 ***
task        2 25.735  12.868  26.821 7.144e-11 ***
age_c:task  2 13.230   6.615  13.789 2.777e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The two interaction coefficients compare each task’s age slope with the reference task’s slope; the ANOVA row tests those two differences together.

Age Slopes by Task

Slope · 기울기SE · standard error · 표준오차CI · confidence interval · 신뢰구간p · p-value · p값
Compare the age slopes by task, then check their confidence intervals and p-values.

Age slopes

if (requireNamespace("modelbased", quietly = TRUE)) {
  slopes <- modelbased::estimate_slopes(
    m_interaction,
    trend = "age_c",
    by = "task"
  )
  print(slopes)
} else {
  cat("Install modelbased to run estimate_slopes().")
}
Estimated Marginal Effects

task               | Coefficient |   SE |       95% CI | t(173) |      p
------------------------------------------------------------------------
Novelty preference |        0.40 | 0.09 | [0.21, 0.58] |   4.26 | < .001
Habituation        |        0.89 | 0.09 | [0.71, 1.08] |   9.56 | < .001
Recognition        |        0.22 | 0.09 | [0.04, 0.41] |   2.41 | 0.017 
Marginal effects estimated for age_c

Estimated coefficients

if (exists("slopes") &&
    requireNamespace("ggplot2", quietly = TRUE)) {
  slope_plot <- plot(slopes) +
    ggplot2::geom_hline(
      yintercept = 0,
      linetype = "dashed",
      colour = "grey50"
    ) +
    ggplot2::labs(
      x = NULL,
      y = "Estimated age slope"
    ) +
    ggplot2::theme_minimal(base_size = 16)

  slope_plot
}

Each row gives the estimated change in looking time for a one-unit increase in centered age within that task. The plot shows the same estimates with confidence intervals.

Contrasts Among Task Levels

Contrast · group difference · 집단 차이SE · standard error · 표준오차CI · confidence interval · 신뢰구간p · p-value · p값
Compare the task differences, then check the arrows and p-values.

Pairwise contrasts for task

if (requireNamespace("modelbased", quietly = TRUE) &&
    requireNamespace("emmeans", quietly = TRUE)) {
  task_contrasts <- modelbased::estimate_contrasts(
    m_interaction,
    contrast = "task",
    backend = "emmeans"
  )
  print(task_contrasts)
} else {
  cat("Install modelbased and emmeans to run the contrasts.")
}
Marginal Contrasts Analysis

Level1             |      Level2 | Difference |         95% CI |   SE | t(173) |      p
---------------------------------------------------------------------------------------
Habituation        | Recognition |      -0.92 | [-1.23, -0.62] | 0.13 |  -7.29 | < .001
Novelty preference | Habituation |       0.39 | [ 0.08,  0.69] | 0.13 |   3.08 | 0.002 
Novelty preference | Recognition |      -0.53 | [-0.84, -0.23] | 0.13 |  -4.22 | < .001

Marginal contrasts estimated at task
p-value adjustment method: Holm (1979)

emmeans comparison arrows

if (requireNamespace("emmeans", quietly = TRUE) &&
    requireNamespace("ggplot2", quietly = TRUE)) {
  task_means <- emmeans::emmeans(
    m_interaction,
    ~ task
  )

  plot(task_means, comparisons = TRUE) +
    ggplot2::labs(
      x = "Estimated looking time",
      y = NULL
    ) +
    ggplot2::theme_minimal(base_size = 16)
}

The table and arrows compare the model-adjusted task means. Because age_c is centered, the reference grid evaluates these comparisons at mean age.