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

두 집단의 평균 차이와 집단 안의 변동을 함께 봅니다.

집단 · group평균 · mean평균 차이 · mean difference변동 · variation표준오차 · standard errort값 · t statistic

보세요비교해 보세요바꿔 보세요확인해 보세요

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.

점 · 관측값 (observed value)가로축 · 집단 (group)세로축 · 결과변수 (outcome)

Group Means

평균 · mean
각 집단의 관측값을 하나의 값으로 요약합니다.
굵은 검은색 선 · 집단 평균 (group mean)점 · 관측값 (observed value)

Between-Group Difference

평균 차이 · mean difference
두 집단 평균 사이의 세로 차이입니다.
검은색 선 · 집단 평균세로 차이 · 평균 차이 (mean difference)

Within-Group Variation

집단 내 변동 · within-group variation
같은 집단 안에서 관측값이 집단 평균과 얼마나 다른지를 나타냅니다.
세로 거리 · 관측값과 집단 평균의 차이검은색 선 · 집단 평균

Uncertainty in the Mean Difference

표준오차 · standard error — 표본이 달라질 때 추정값이 얼마나 달라질 수 있는지 나타냅니다.
신뢰구간 · confidence interval — 평균 차이 추정의 불확실성을 나타내는 범위입니다.
주황색 점 · 추정값 (estimate)주황색 선 · 95% 신뢰구간

The t Statistic

t값 · t statistic
평균 차이를 그 차이의 표준오차로 나눈 값입니다: 추정값 ÷ 표준오차.

Interactive Two-Group Comparison

1 · 보세요두 집단의 점과 평균
2 · 비교해 보세요평균 차이와 집단 내 변동
3 · 바꿔 보세요평균 차이, SD, 표본 크기
4 · 확인해 보세요t값, p값, 신뢰구간

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

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

점 · 관측값굵은 검은색 선 · 집단 평균주황색 점과 선 · 추정값과 95% 신뢰구간

Unit 2 — Two Groups as a Linear Model

두 조건을 0과 1로 코딩하고, 평균 차이를 선형모형의 계수로 나타냅니다.

예측변수 · predictor절편 · intercept기울기 · slope계수 · coefficient적합값 · fitted value잔차 · residual

보세요: 두 적합값 → 비교해 보세요: 0과 1 → 바꿔 보세요: 기준집단 → 확인해 보세요: 계수

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
결과변수의 차이나 변화를 설명하기 위해 모형에 넣는 변수입니다. 여기서는 두 조건을 X=0과 X=1로 표시합니다.

The Intercept

절편 · intercept (β₀)
X=0일 때의 적합값입니다.

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

The Fitted Line

적합선 · fitted line
X=0과 X=1에서 모형이 추정한 적합값을 연결한 선입니다.
검은색 선 · 적합선검은색 점 · 적합값 (fitted value)파란색 점 · 관측값

The Coefficient as the Change from 0 to 1

기울기 · slope β₁ = 적합값의 변화 ÷ X의 변화 = (56.00 − 50.25) ÷ (1 − 0) = 5.75

계수 · coefficient
이 0/1 모형에서 β₁은 X가 0에서 1로 바뀔 때의 적합값 변화이며, 두 집단의 평균 차이와 같습니다.

Residual Distance from the Fitted Line

잔차 · residual eᵢ = 관측값 observed Yᵢ − 적합값 fitted Ŷᵢ

잔차 · residual
점과 적합선 사이의 세로 거리입니다: 관측값 − 적합값.
주황색 점 · 관측값검은색 점 · 적합값주황색 세로 거리 · 잔차

Components of the Two-Group Linear Model

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

β₀ · 절편 · X=0의 적합값 β₁ · 기울기 · X=0에서 1로의 변화 eᵢ · 잔차 · 세로 거리

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.

파란색 음영 · 적합선 ± 잔차 SD검은색 선 · 적합선점 · 관측값

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 · 보세요두 적합값과 검은색 선
2 · 비교해 보세요0과 1의 위치
3 · 바꿔 보세요기준집단
4 · 확인해 보세요절편, 기울기, p값

Unit 3 — Comparing Several Groups

세 집단 이상의 평균을 비교하고, 집단 사이와 집단 안의 변동을 F값으로 비교합니다.

집단 사이 변동 · between-group variation집단 내 변동 · within-group variationF값 · F statistic기준집단 · reference group지시변수 · indicator variable

보세요: 세 평균 → 비교해 보세요: 두 변동 → 바꿔 보세요: 평균과 SD → 확인해 보세요: F값과 p값

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값 · F statistic
집단 사이 변동을 집단 내 변동으로 나눈 값입니다.
굵은 검은색 선 · 집단 평균점 · 관측값

Between-Group Variation

집단 사이 변동 · between-group variation
각 집단 평균이 전체 평균에서 얼마나 떨어져 있는지를 나타냅니다. F값의 분자입니다.
점선 · 전체 평균 (grand mean)굵은 선 · 집단 평균세로 거리 · 집단 사이 변동

Within-Group Variation

집단 내 변동 · within-group variation
개별 관측값이 자기 집단 평균에서 얼마나 떨어져 있는지를 나타냅니다. F값의 분모입니다.
세로 거리 · 집단 내 변동굵은 선 · 집단 평균점 · 관측값

Interactive Group Means and Within-Group Spread

1 · 보세요세 집단의 평균
2 · 비교해 보세요집단 사이·집단 내 변동
3 · 바꿔 보세요평균, SD, 표본 크기
4 · 확인해 보세요F값, p값, 계수

F = between-group variation within-group variation

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

점선 · 설정한 집단 평균굵은 선 · 표본 평균점 · 관측값

Try the Three-Condition Prediction

1 · 보세요기준집단과 모형식
2 · 비교해 보세요두 지시변수
3 · 바꿔 보세요X₁, X₂, 예측값
4 · 확인해 보세요입력한 답

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

기준집단 · reference group — 다른 집단의 계수를 해석할 때 비교 기준이 되는 집단입니다. 지시변수 · indicator variable — 해당 집단이면 1, 아니면 0으로 표시합니다.

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

Unit 4 — Continuous Predictors and Linear Regression

예측변수가 연속형일 때 기울기, 잔차, 신뢰구간을 그래프에서 찾습니다.

연속형 예측변수 · 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
여러 수치값을 가질 수 있는 예측변수입니다. X가 한 단위 증가할 때 결과변수의 기대 변화가 기울기입니다.
점 · 관측값검은색 선 · 회귀선가로축 · 예측변수세로축 · 결과변수

Slope on the Fitted Line

기울기 · slope
예측변수 X가 한 단위 증가할 때 결과변수 Y의 기대 변화입니다: 세로 변화(rise) ÷ 가로 변화(run).
가로 화살표 · X의 변화 (run)세로 화살표 · 적합값의 변화 (rise)검은색 선 · 회귀선

Residuals on the Fitted Line

잔차 · residual
점과 적합선 사이의 세로 거리입니다: 관측값 − 적합값.
주황색 점 · 관측값주황색 세로 화살표 · 잔차검은색 선 · 적합선

Uncertainty Around the Fitted Line

신뢰구간 · confidence interval
평균의 추정이 불확실한 정도를 나타내는 범위입니다. 가운데에서 좁고 양 끝에서 넓어집니다.
파란색 음영 · 평균의 95% 신뢰구간검은색 선 · 적합선점 · 관측값

Interactive Slope, Residuals, and Precision

1 · 바꿔 보세요기울기
2 · 비교해 보세요점과 선의 거리
3 · 늘려 보세요표본 크기
4 · 확인해 보세요신뢰구간과 p값

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

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

점 · 관측값세로 거리 · 잔차주황색 선 · 적합선파란색 음영 · 95% 신뢰구간

Unit 5 — Adjustment and Multiple Regression

두 변수의 관계가 나이와 같은 다른 변수 때문에 달라 보이는지 확인하고, 조정된 관계를 추정합니다.

원자료 관계 · raw association조정된 관계 · adjusted association통제하다 · control계수 · 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
나이가 비슷한 아동끼리 비교하여, 대화 차례와 언어점수의 관계를 추정합니다.
점 · 관측값검은색 선 · 원자료 관계 (raw association)점의 색 · 나이

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 — 나이를 조정하지 않은 전체 관계입니다.
조정된 관계 · adjusted association — 나이가 비슷할 때의 관계입니다.

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.
통제하다 · control / hold constant
다른 예측변수가 같은 값이라고 두고 한 계수를 해석합니다. 여기서는 인과효과를 의미하지 않습니다.

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 · 보세요점의 색과 원자료 선
2 · 비교해 보세요원자료 계수와 조정 계수
3 · 바꿔 보세요나이 효과와 상관
4 · 확인해 보세요두 계수와 p값

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

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

검은색 선 · 원자료 관계초록색 막대 · 조정 계수회색 막대 · 원자료·설정 계수점의 색 · 나이

Unit 6 — Interaction and Conditional Effects

한 예측변수의 효과가 다른 변수의 값에 따라 달라지는지 상호작용으로 확인합니다.

주효과 · 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?
젊은 집단과 나이 든 집단에서 두 조건 사이의 세로 간격을 먼저 비교해 보세요.
상호작용 · interaction — 조건 효과가 연령집단에 따라 달라집니다: 젊은 집단에서는 8점, 나이 든 집단에서는 16점입니다.
세로 간격 · 조건의 단순효과선 · 조건별 적합값

Main Effects, Simple Effects, and Interaction

Interactive Simple Slopes with Continuous Age

1 · 보세요세 연령의 적합선
2 · 비교해 보세요세 단순기울기
3 · 바꿔 보세요상호작용 계수
4 · 확인해 보세요기울기와 p값

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)

점 · 관측값색이 다른 선 · 연령별 적합선선의 기울기 · 단순기울기

Unit 7 — Generalized Linear Models

결과변수의 종류에 맞게 확률 또는 기대 횟수를 예측합니다.

이진 결과변수 · binary outcome횟수 결과변수 · count outcome확률 · probability기대 횟수 · expected count이항분포 · binomial distribution포아송분포 · Poisson distribution

보세요: 가능한 결과 → 비교해 보세요: 곡선과 분포 → 바꿔 보세요: 기울기 → 확인해 보세요: 예측값과 p값

Valid Predictions for Different Outcomes

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

결과변수 · outcome분석에서 설명하거나 예측하려는 변수
연속형 결과변수 · 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계수와 예측변수를 결합한 값; 결과변수의 종류에 맞는 척도로 변환합니다.
연속형 결과변수 · 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정해진 시행 횟수에서 성공 횟수의 가능한 값과 확률
검은색 곡선 · 예측확률파란색 막대 · 이항분포세로 점선 · 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일정한 구간에서 관측될 횟수의 가능한 값과 확률
검은색 곡선 · 기대 횟수주황색 막대 · 포아송분포세로 점선 · X = 3

Interactive Logistic Prediction

1 · 보세요확률 곡선과 이항분포
2 · 비교해 보세요X=1과 X=4의 확률
3 · 바꿔 보세요절편, 기울기, 표본 크기
4 · 확인해 보세요예측확률과 p값

Change the slope first, then the number of children.

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

파란색 점 · 관측값주황색 곡선 · 적합확률파란색 막대 · 이항분포

Interactive Poisson Prediction

1 · 보세요기대 횟수 곡선과 포아송분포
2 · 비교해 보세요X=1과 X=4의 기대 횟수
3 · 바꿔 보세요절편, 기울기, 표본 크기
4 · 확인해 보세요기대 횟수와 p값

Change the slope first, then the number of children.

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

파란색 점 · 관측 횟수주황색 곡선 · 기대 횟수주황색 막대 · 포아송분포

Unit 8 — Repeated Observations and Mixed Effects

같은 아동에게서 반복해서 측정한 값의 의존성과 아동 사이·아동 내 변동을 구분합니다.

반복측정 · 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같은 참여자에게서 두 번 이상 측정한 값

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

점 · 방문별 관측값연결선 · 아동별 변화가로축 · 방문세로축 · 결과변수

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 아동별 임의 절편 · 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각 아동의 전체적인 높고 낮은 경향을 나타내는 항

Interactive: Within- and Between-Child Variation

1 · 보세요아동별 점과 선
2 · 비교해 보세요아동 사이·아동 내 변동
3 · 바꿔 보세요SD, 아동 수, 방문 수
4 · 확인해 보세요기울기와 p값

Change between-child and within-child SD separately.

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

파란색 선 · 아동별 궤적검은색 선 · 전체 적합선가로축 · 나이세로축 · 결과변수

Putting the Models Together

먼저 결과변수연구 구조를 확인한 뒤 모형을 선택합니다.
결과변수 · outcome예측변수 · predictor반복측정 · repeated observations모형 선택 · model choice
보세요: 결과변수 → 비교해 보세요: 가능한 모형 → 바꿔 보세요: 연구 조건 → 확인해 보세요: R 모형식

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 · 보세요연구 설명
2 · 비교해 보세요결과변수와 예측변수
3 · 바꿔 보세요A–D의 선택
4 · 확인해 보세요Check를 눌러 결과 확인

Thank You

Bonus Content

Actual R output from a reproducible simulated child-listening dataset

Estimate추정값Std. Error표준오차t value추정값 ÷ 표준오차Pr(>|t|)p값
먼저 Estimate를 보세요. 다음으로 p값을 확인해 보세요.

Simple Regression and the t-Test

먼저 Estimate를 보세요. 다음으로 t value와 p값을 비교해 보세요.

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

계수표의 각 Estimate를 보세요. 그다음 ANOVA의 모형 항과 p값을 확인해 보세요.

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

상호작용 계수의 Estimate를 보세요. 그다음 ANOVA의 age_c:task p값을 확인해 보세요.

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표준오차CI신뢰구간pp값
과제별 기울기를 비교해 보세요. 신뢰구간과 p값을 확인해 보세요.

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집단 차이SE표준오차CI신뢰구간pp값
과제 사이의 차이를 보세요. 화살표와 p값을 확인해 보세요.

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.