How To Run An Anova In R

9 min read

Learning how to run an ANOVA in R is an essential skill for students, researchers, and data analysts who need to compare means across three or more groups. Even so, analysis of Variance, commonly known as ANOVA, allows you to determine whether statistically significant differences exist between group means while accounting for variability within each group. In this guide, you will walk through the complete process of running an ANOVA in R, from checking assumptions to interpreting results and performing post-hoc tests.

What Is ANOVA and When Should You Use It?

ANOVA is a statistical method used to test differences between two or more group means. While a t-test works well for comparing two groups, ANOVA extends that logic to multiple groups without inflating the risk of Type I errors.

You should use ANOVA when:

  • You have one continuous dependent variable.
  • You have one or more categorical independent variables (factors).
  • You want to compare the means of three or more independent groups.
  • Your data meet the underlying assumptions of the test.

The most common versions are one-way ANOVA (one independent variable) and two-way ANOVA (two independent variables). In R, the base aov() function and the anova() function make it straightforward to fit these models.

Preparing Your Data for ANOVA in R

Before running any statistical test, your data must be structured correctly. R works best with data frames where each row represents an observation and each column represents a variable.

Create or Import Your Dataset

You can enter data manually or import it from a CSV file:

# Manual data entry
data <- data.frame(
  group = factor(rep(c("Control", "Treatment A", "Treatment B"), each = 10)),
  score = c(85, 88, 90, 87, 86, 89, 91, 88, 87, 89,
            78, 82, 80, 79, 81, 83, 77, 80, 82, 79,
            92, 94, 93, 95, 91, 93, 96, 94, 92, 95)
)

# Or import from CSV
# data <- read.csv("your_file.csv")

The group column must be a factor. If it is stored as character or numeric, convert it using factor() so R treats it as a categorical variable.

Inspect the Data

Always inspect your data before modeling:

head(data)
str(data)
summary(data)

This helps confirm that your factor levels are correct and that there are no missing values in the dependent variable Less friction, more output..

Running a One-Way ANOVA in R (Step-by-Step)

A one-way ANOVA tests whether the means of a single dependent variable differ across levels of one factor Not complicated — just consistent..

Step 1: Load and Inspect Your Data

Use the dataset created above. Make sure group is a factor and score is numeric.

Step 2: Fit the ANOVA Model

The most common way to run ANOVA in R is with the aov() function:

anova_model <- aov(score ~ group, data = data)

The formula score ~ group tells R to model score as a function of group Simple, but easy to overlook..

Step 3: Interpret the ANOVA Table

To view the results, use summary():

summary(anova_model)

The output will include:

  • Df: Degrees of freedom for the factor and residuals.
  • Sum Sq: Sum of squares.
  • Mean Sq: Mean square (Sum Sq divided by Df).
  • F value: The F-statistic.
  • Pr(>F):

the p-value associated with the F-statistic. This is the primary value used to determine statistical significance. If Pr(>F) < 0.05 (or your chosen alpha level), you reject the null hypothesis and conclude that there is a statistically significant difference between at least two group means That's the part that actually makes a difference..

Short version: it depends. Long version — keep reading.

Checking ANOVA Assumptions

ANOVA relies on three key assumptions. Violating them can lead to misleading results, so you must verify them before trusting your p-value.

1. Independence of Observations

This is a study design issue, not a testable property of the data. Ensure your groups are independent (e.g., different subjects in each group) and observations within groups are not correlated (e.g., no repeated measures on the same subject unless using a repeated-measures ANOVA).

2. Normality of Residuals

ANOVA assumes the residuals (errors) are normally distributed, not necessarily the raw data within each group.

# Extract residuals
residuals <- residuals(anova_model)

# Visual check: Q-Q plot
qqnorm(residuals)
qqline(residuals, col = "red")

# Formal test: Shapiro-Wilk
shapiro.test(residuals)

If the p-value from shapiro.test() is > 0.05, you fail to reject the null hypothesis of normality. With large sample sizes, ANOVA is dependable to minor deviations from normality Easy to understand, harder to ignore..

3. Homogeneity of Variances (Homoscedasticity)

The variance of the dependent variable should be roughly equal across all groups.

# Levene's Test (from car package)
# install.packages("car")
library(car)
leveneTest(score ~ group, data = data)

A non-significant result (p > 0.05) indicates equal variances. If this assumption is violated, consider using Welch’s ANOVA (oneway.test(score ~ group, data = data)), which does not assume equal variances.

Post-Hoc Pairwise Comparisons

A significant ANOVA tells you that a difference exists, but not where it lies. You must run post-hoc tests to identify specific group differences while controlling the family-wise error rate That's the part that actually makes a difference..

Tukey’s HSD (Honestly Significant Difference)

The standard choice for equal sample sizes and variances.

tukey_results <- TukeyHSD(anova_model)
tukey_results
plot(tukey_results) # Visualizes confidence intervals for mean differences

Look for comparisons where the adjusted p-value (p adj) is < 0.05. Confidence intervals that do not cross zero indicate significance.

Alternative: Games-Howell Test

If Levene's test was significant (unequal variances), Tukey's HSD is inappropriate. Use the games_howell_test() from the rstatix package instead.

# install.packages("rstatix")
library(rstatix)
games_howell_test(data, score ~ group)

Calculating Effect Size

Statistical significance does not equal practical importance. Report Eta-squared (η²) or Partial Eta-squared (ηp²) to quantify the proportion of variance explained by the factor.

# install.packages("effectsize")
library(effectsize)
eta_squared(anova_model)
  • 0.01: Small effect
  • 0.06: Medium effect
  • 0.14: Large effect

Running a Two-Way ANOVA

When you have two categorical independent variables (e.g., treatment and gender), a two-way ANOVA assesses main effects for each factor and their interaction effect.

# Example data with two factors
data2 <- data.frame(
  score = c(85, 88, 78, 82, 92, 94, 75, 78, 88, 90, 80, 82),
  treatment = factor(rep(c("Drug", "Placebo"), each = 6)),
  gender = factor(rep(c("Male", "Female"), times = 6))
)

# Model with interaction term (*)
model_2way <- aov(score ~ treatment * gender, data = data2)
summary(model_2way)

The output will show three rows: treatment, gender, and treatment:gender (the interaction).

  • Significant Interaction: The effect of one factor depends on the level of the other. Do not interpret main effects in isolation; use simple effects analysis or interaction plots (interaction.plot()).
  • Non-significant Interaction: You can drop the interaction term and refit an additive model (score ~ treatment + gender) to interpret main effects cleanly.

Reporting Your Results

A complete results section includes:

  1. That said, 2, p = . Assumption checks: Statement on normality and homogeneity (e.Here's the thing — 31"). , "Levene's test was non-significant, F(2, 27) = 1.Also, 2. Even so, ANOVA result: F-statistic, degrees of freedom, p-value, and effect size (e. On top of that, g. Descriptive statistics: Means and SDs per group.
  2. g.

Reporting the ANOVA result

A complete statistical report should present the ANOVA table in a concise, reader‑friendly format. The following template can be adapted to any factor:

A one‑way ANOVA revealed a significant effect of [Factor] on [Dependent Variable],
F([df_between], [df_within]) = [F‑value], p = [p‑value], η² = [eta‑squared].

To give you an idea, using the data set from the earlier one‑way example:

# Assuming anova_model is the aov() object from the one‑way analysis
anova_table <- summary(anova_model)[[1]]
df_between <- anova_table[" treatment", "df"]
df_within  <- anova_table[" treatment", "Df"] + anova_table["Residuals", "Df"]
F_val       <- anova_table[" treatment", "F value"]
p_val       <- anova_table[" treatment", "Pr(>F)"]
eta_sq     <- eta_squared(anova_model) %>% pull(eta_sq)

cat(sprintf(
  "A one‑way ANOVA revealed a significant effect of Treatment on Score,\n"
  %>% paste0("F(%d, %d) = %.3f, p = %.3f, η² = %.3f.

The output will look like:

A one‑way ANOVA revealed a significant effect of Treatment on Score, F(2, 27) = 5.312, p = .012, η² = .283 Worth knowing..


**Interpreting η² (or partial η²)**  
The magnitude guidelines (small ≈ 0.01, medium ≈ 0.06, large ≈ 0.14) are useful heuristics, but always interpret the effect size in the context of the research question. An η² of .283, for instance, indicates that roughly 28 % of the variance in the dependent variable is accounted for by the factor of interest—a substantively meaningful effect.

**Checking assumptions visually**

Even when formal tests (e.Also, g. , Levene’s test) are non‑significant, it is good practice to inspect residual plots. 

```r
# Residual vs. fitted plot
plot(resid(anova_model), fitted(anova_model),
     xlab("Fitted values"), ylab("Residuals"),
     main = "Residual diagnostic for one‑way ANOVA")

A random scatter around the horizontal line suggests homoscedasticity; any funnel shape may warrant transformation (e.g., log or square‑root) or a switch to a dependable alternative such as the Games‑Howell test And that's really what it comes down to. And it works..

When to prefer Games‑Howell over Tukey HSD

If Levene’s test flags unequal variances, the Tukey HSD confidence intervals may be too liberal. The Games‑Howell procedure controls the family‑wise error rate under heteroscedasticity and is straightforward to invoke:

games_howell_results <- games_howell_test(data$score, data$group)
print(games_howell_results)

The output includes mean differences, standard errors, confidence intervals, and an adjusted p‑value (p_adj). Also, as with Tukey, any comparison with p_adj < . 05 is taken as statistically significant.

Two‑way ANOVA – reporting main effects and interaction

When the interaction term (treatment:gender) is significant, the interpretation shifts to simple effects:

# Simple effects analysis for significant interaction
library(emmeans)
emmeans(model_2way, ~ treatment | gender)   # estimated means per gender
contrast(emmeans(model_2way, ~ treatment | gender), pairwise)  # pairwise contrasts within each gender

If the interaction is non‑significant, you may refit an additive model and simply report the main effects:

model_additive <- aov(score ~ treatment + gender, data = data2)
summary(model_additive)

Putting it all together – a reproducible workflow

# -------------------------------------------------
# 1. Load data and packages
# -------------------------------------------------
library(tidyverse)
library(car)          # for Levene's test
library(emmeans)      # for post‑hoc & simple effects
library(rstatix)      # for Games‑Howell
library(effectsize)   # for η²
# -------------------------------------------------
# 2. Basic inspection
# -------------------------------------------------
data <- read_csv("your_data.csv") %>%
  mutate(group = factor(group),
         outcome = factor(outcome))

describe_by(data$score, data$group) %>% summarise(mean = mean(), sd = sd())

# -------------------------------------------------
# 3. Assumption checks
# -------------------------------------------------
levene_test(score ~ group, data
Dropping Now

Newly Added

Similar Territory

Good Reads Nearby

Thank you for reading about How To Run An Anova In R. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home