1. What is two-way ANOVA test?

Two-way ANOVA test is used to evaluate simultaneously the effect of two grouping variables (A and B) on a response variable. The grouping variables are also known as factors. The different categories (groups) of a factor are called levels. The number of levels can vary between factors. The level combinations of factors are called cell. When the sample sizes within cells are equal, we have the so-called balanced design.

2. Check whether data are balanced

To see if your data are balanced, you can use the function:

# Are observations in the poopdeck data balanced?
with(poopdeck,
     table(cleaner, type))
##        type
## cleaner parrot shark
##       a    100   100
##       b    100   100
##       c    100   100

As you can see, in the poopdeck data, the observations are perfectly balanced, so it doesnโ€™t matter which type of ANOVA we use to analyse the data.

3. Balanced Two-way ANOVA Test

Type 1: when data are balanced

# Type I ANOVA - aov()
data.aov <- aov(data)

4. Unbalanced Two-way ANOVA Test

The function Anova() [in car package] can be used to compute two-way ANOVA test for unbalanced designs.

Type2: data are unbalanced and has no significant interaction effect

# Type II ANOVA - Anova(type = 2)
time.II.aov <- Anova(aov(data), type = 2)

Type3: data are unbalanced and has significant interaction effect

# Type III ANOVA - Anova(type = 3)
data.aov <- Anova(aov(data), type = 3)

To check the pairwise comparison for unbalanced data, use emmeans::emmeans().

Alert: Check the class of variable first, then proceed Anova or emmeans test! For example:

str(tomato$containersize)
tomato$containersize <- as.factor(tomato$containersize)
Rdep_anova <- aov(Rdepth ~ salinity * fruiting * containersize, data = tomato)
Anova(Rdep_anova , type = 2)
emmeans(Rdep_anova, pairwise~containersize)

5. Export ANOVA table:

Here is a solution for an Anova table using the command capture.output():

Rdep_anova <- aov(Rdepth3 ~ variety * fertilizer, data = S3_valid)
Anova(my_anova, type = 2)
capture.output(Anova(my_anova, type = 2), file="test.doc")

For more detail on this topic, check out:
(1) Two-Way ANOVA Test in R
(2) Type I, Type II, and Type III ANOVAs
(3) Factorial ANOVA
(4) Factorial and Unbalanced Analysis of Variance
(5) Analyses of Two-Factor Unbalanced and Incomplete Designs in R
(6) Three-way ANOVA Interaction analysis in emmeans
(7) When Unequal Sample Sizes Are and Are NOT a Problem in ANOVA