R aov() Function - Analysis of Variance
The R aov() function is used to perform analysis of variance (ANOVA), comparing whether the means of three or more groups differ significantly.
When more than two groups need to be compared, using ANOVA is more appropriate than multiple t-tests.
The syntax of the aov() function is as follows:
aov(formula, data)
Parameter Description:
-
formula A formula in the form response variable ~ grouping variable.
-
data A data frame containing the variables in the formula.
Example
The 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 a data frame
df
<-
data.frame
(
fertilizer, yield
)
(
"Data Preview:"
)
(
df
)
Perform analysis of variance
result
<-
aov
(
yield ~ fertilizer,
data
=
df
)
(
summary
(
result
)
)
The output of the code above is:
[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 a highly significant difference in the effect of the three fertilizers on yield.
R Language Examples