RStudio面板展示
配套代码
#方差分析
#单因素方差分析
install.packages("multcomp") # 安装 multcomp 包
library(multcomp) # 加载 multcomp 包
cholesterol
attach(cholesterol) # 使用 attach 函数将数据框 cholesterol 中的变量附加到搜索路径中
table(trt) # 显示 trt 变量的频数表
aggregate(response,by=list(trt),FUN=mean) # 按照 trt 变量的水平计算 response 变量的平均值,根据结果发现E组效果最好
fit <- aov(response~trt,data=cholesterol) # 对 response 变量进行单因素方差分析,使用 trt 作为因子
fit
summary(fit) # 方差结果分析主要看F值和P值,F值越大说明组间差异越显著,P值越小越精确
plot(fit) # 绘制方差分析的拟合结果图形
fit.lm <- lm(response~trt,data=cholesterol) #l利用lm进行方差分析
fit.lm
summary(fit.lm) #与上面分析结果一致
#单因素协方差示例 #怀孕小鼠数据,因为怀孕小鼠生崽的时间有所不同会影响体重,因此属于协变量
litter
table(litter$dose) #统计分组情况
attach(litter) # 使用 attach 函数将数据框 cholesterol 中的变量附加到搜索路径中
aggregate(weight,by=list(dose),FUN=mean) # 按照 dose 变量的水平计算weight变量的平均值,根据结果发现不同处理组平均体重不同
fit <- aov(weight ~ gesttime + dose,data = litter) #利用方差分析检验不同药物组是否显著差别,因变量weight ,协变量 gesttime ,自变量 dose
summary(fit) #结果表明怀孕时间与幼崽体重相关,控制怀孕时间,药物剂量与小鼠体重有关
#双因素方差分析 实验设计中有两个变量
ToothGrowth #抽取六十只小鼠,采用橙汁和VC两种不同喂食方法,采用不同剂量,哪种促进牙齿生长更显著
attach(ToothGrowth ) # 使用 attach 函数将数据框 ToothGrowth 中的变量附加到搜索路径中
xtabs(~supp+dose) # 显示 supp、dose 变量的频数表
aggregate(len,by=list(supp,dose),FUN=mean) # 按照 len 变量的水平计算supp,dose变量的平均值,根据结果剂量越小两者差距越显著
ToothGrowth$dose <- factor(ToothGrowth$dose) # 将 ToothGrowth 数据框中的 dose 列转换为因子(factor)
class(ToothGrowth$dose) # 显示转换后 dose 列的数据类型
fit <- aov(len ~ supp*dose,data=ToothGrowth) # 对len 变量进行两因子方差分析,supp*dose等于supp+doses+upp:dose
summary(fit) #结果表明supp,dose两个变量结果显著,不同药物不同剂量对牙齿生长均有显著影响
install.packages("HH") #效果展示
library(HH)
interaction.plot(
dose, supp, len,
type = "b", col = c("red", "blue"), pch = c(16, 18),
main = "Interaction between Dose and Supplement Type") #刚开始橙汁效果更明显,当剂量达到2毫克时两者效果相同
# 使用 interaction.plot 函数绘制交互作用图。 参数说明:dose: 数据中的因子变量,用于横坐标
# supp: 数据中的因子变量,用于生成不同的曲线
# len: 数据中的响应变量,纵坐标的值
# type: 绘制的图形类型,"b" 表示同时绘制点和线
# col: 指定曲线的颜色,以向量形式提供,这里使用红色和蓝色
# pch: 指定点的形状,以向量形式提供,这里使用圆点(16)和方块点(18)
# main: 图形的主标题
#多元数据分析
library(MASS)
UScereal
attach(UScereal) # 使用 attach 函数将数据框 UScereal 中的变量附加到搜索路径中
shelf <- factor(shelf) # 将 shelf列转换为因子
aggregate(cbind(calories,fat,sugars),by=list(shelf),FUN=mean) # 按照 shelf变量的水平计算calories,fat,sugars变量的平均值
fit <- manova(cbind(calories,fat,sugars) ~ shelf) #对 calories、fat 和 sugars 这三个变量进行多元方差分析(MANOVA) cbind(calories,fat,sugars)将三列合成一个对象
fit
summary.aov(fit) # 对 MANOVA 拟合结果进行单因素方差分析(ANOVA)的摘要信息