R aov() Function - ANOVA

R 语言实例R Language Examples

The R aov() function is used to perform analysis of variance (ANOVA) to compare whether there are significant differences among the means of three or more groups.

When there are more than two groups of data to compare, using ANOVA is more appropriate than multiple t-tests.

The syntax of the aov() function is as follows:

aov(formula, data)

Parameter description:

  • formulaFormula, in the format response variable ~ grouping variable.

  • dataData frame, containing the variables in the formula.

Example

# Effect of three fertilizers on crop yield
fertilizer <- factor(rep(c("A", "B", "C"), each = 5))
yield <- c(18, 20, 19, 22, 21,     # Fertilizer A
           25, 27, 24, 26, 28,     # Fertilizer B
           15, 17, 16, 14, 18)     # Fertilizer C

# Create data frame
df <- data.frame(fertilizer, yield)
print("Data preview:")
print(df)

# Perform ANOVA
result <- aov(yield ~ fertilizer, data = df)
print(summary(result))

Running the above code produces the following output:

[1] "数据预览:"
   fertilizer yield
1           A    18
2           A    20
3           A    19
4           A    22
5           A    21
6           B    25
...
            Df Sum Sq Mean Sq F value   Pr(>F)
fertilizer   2  190.0   95.00   28.61 2.73e-05 ***
Residuals   12   39.9    3.32
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The p-value is far less than 0.001, indicating that the three fertilizers have a highly significant difference in their effects on yield.

R 语言实例R Language Examples

Other Extensions