R语言 方差分析测试

R语言 方差分析测试

ANOVA也被称为方差分析,用于研究R编程中分类变量和连续变量之间的关系。它是一种对群体方差的假设检验。

R – 方差分析测试

方差分析测试包括设置。

  • 无效假设: 所有种群平均数都相等。
  • 备选假设: 至少有一个群体的平均数与其他群体不同。

方差分析测试有两种类型。

  • 单向方差分析: 它考虑到一个分类组。
  • 双向方差分析: 它考虑了两个分类组的情况。

数据集

我们使用了MTCars(motor trend car road test)数据集,其中包括32个汽车品牌和11个属性。该数据集预先安装在R的 dplyr 包中。

为了开始使用方差分析,我们需要安装并加载 dplyr 包。

在R语言中执行单程方差分析测试

使用预先安装了dplyr包的MTCars数据集,在连续属性disp和分类属性gear之间进行单程方差分析测试。

# Installing the package
install.packages("dplyr")
 
# Loading the package
library(dplyr)
 
# Variance in mean within group and between group
boxplot(mtcarsdisp~factor(mtcarsgear),
        xlab = "gear", ylab = "disp")
 
# Step 1: Setup Null Hypothesis and Alternate Hypothesis
# H0 = mu = mu01 = mu02(There is no difference
# between average displacement for different gear)
# H1 = Not all means are equal
 
# Step 2: Calculate test statistics using aov function
mtcars_aov <- aov(mtcarsdisp~factor(mtcarsgear))
summary(mtcars_aov)
 
# Step 3: Calculate F-Critical Value
# For 0.05 Significant value, critical value = alpha = 0.05
 
# Step 4: Compare test statistics with F-Critical value
# and conclude test p < alpha, Reject Null Hypothesis

输出

R编程中的方差分析测试

箱形图显示了齿轮的平均值与位移的关系。听力分类变量是齿轮,因子函数被用于此,连续变量是位移。

R编程中的方差分析测试

总结显示,齿轮属性对位移非常显著(三颗星表示)。另外,P值小于0.05,所以证明齿轮与位移是显著的,也就是相互关联的,我们拒绝无假设。

在R中进行双向方差分析测试

使用预先安装了dplyr软件包的MTCars数据集,在连续属性disp和分类属性gear、分类属性am之间进行双向方差检验。

# Installing the package
install.packages("dplyr")
 
# Loading the package
library(dplyr)
 
# Variance in mean within group and between group
boxplot(mtcarsdisp~mtcarsgear, subset = (mtcarsam == 0),
        xlab = "gear", ylab = "disp", main = "Automatic")
boxplot(mtcarsdisp~mtcarsgear, subset = (mtcarsam == 1),
            xlab = "gear", ylab = "disp", main = "Manual")
 
# Step 1: Setup Null Hypothesis and Alternate Hypothesis
# H0 = mu0 = mu01 = mu02(There is no difference between
# average displacement for different gear)
# H1 = Not all means are equal
 
# Step 2: Calculate test statistics using aov function
mtcars_aov2 <- aov(mtcarsdisp~factor(mtcarsgear) *
                            factor(mtcars$am))
summary(mtcars_aov2)
 
# Step 3: Calculate F-Critical Value
# For 0.05 Significant value, critical value = alpha = 0.05
 
# Step 4: Compare test statistics with F-Critical value
# and conclude test p < alpha, Reject Null Hypothesis

输出

R编程中的方差分析测试

箱形图显示了齿轮相对于位移的平均值。听到的分类变量是齿轮和am,对其使用了因子函数,连续变量是disp。

R编程中的方差分析测试

总结显示,齿轮属性对位移非常显著(三颗星表示),AM属性对位移不大显著。齿轮的P值小于0.05,所以它证明了齿轮对位移是显著的,即相互关联的。凸轮的P值大于0.05,证明凸轮与位移的关系不明显,即相互之间没有关系。

结果

我们从图表和总结中看到显著的结果。

  • 排量与汽车的齿轮密切相关,即排量取决于齿轮,P<0.05。
  • 排量与齿轮密切相关,但与汽车的传输模式无关,p 0.05。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程