R语言单因素、多因素方差分析ANOVA analysis of variance

Python013

R语言单因素、多因素方差分析ANOVA analysis of variance,第1张

@[toc]

假设检验的前提是要满足正态分布和方差齐性

组内平方和SSE:同一组内的数据误差平方和

组间平方和SSA:不同组之间的数据误差平方和

一个分类型自变量

例如四个班级学生的语文成绩,班级是分类型自变量,四个班级是自变量的四个水平

测试班级对成绩的影响

因为p<0.001,说明班级对成绩的影响非常显著

图中跨越0分界线的班级对,有较大可能落在0上,也就是说两个班级之间没有明显差异。其他班级说明都有明显差异。

同一班级在大学三年的三次测试

p<0.001,说明学生成绩在大学三年中有显著差异。球形检验的p-value大于0.05,所以可以认为方差相等。

Mauchly's Test for Sphericity :适用于重复测量时检验不同测量之间的差值的方差是否相等,用于三次以及三次之上。

Sphericity Corrections :球形矫正,当方差不相等时进行矫正,矫正方法有the Greenhouse-Geisser (1959), the Huynh-Feldt (1976), 简称GG和HF。

两个分类型自变量

例如探究 词汇量 话题熟悉度 对学生作文成绩的影响

词汇量和话题熟悉度两个变量对成绩的影响都很显著,交互项对成绩影响不显著。

探究班级和测试次数对学生成绩的影响

班级和测试次数在原始检验中都很显著,然后交叉项不显著。

但是在球形检验中,推翻了方差齐性的假设,所以tests需要使用球形矫正之后的p值,classes不用。

矫正之前tests的p-value = 3.482406e-04,矫正之后的p-value = 0.001左右。

R语言基本数据分析

本文基于R语言进行基本数据统计分析,包括基本作图,线性拟合,逻辑回归,bootstrap采样和Anova方差分析的实现及应用。

不多说,直接上代码,代码中有注释。

1. 基本作图(盒图,qq图)

#basic plot

boxplot(x)

qqplot(x,y)

2. 线性拟合

#linear regression

n = 10

x1 = rnorm(n)#variable 1

x2 = rnorm(n)#variable 2

y = rnorm(n)*3

mod = lm(y~x1+x2)

model.matrix(mod) #erect the matrix of mod

plot(mod) #plot residual and fitted of the solution, Q-Q plot and cook distance

summary(mod) #get the statistic information of the model

hatvalues(mod) #very important, for abnormal sample detection

3. 逻辑回归

#logistic regression

x <- c(0, 1, 2, 3, 4, 5)

y <- c(0, 9, 21, 47, 60, 63) # the number of successes

n <- 70 #the number of trails

z <- n - y #the number of failures

b <- cbind(y, z) # column bind

fitx <- glm(b~x,family = binomial) # a particular type of generalized linear model

print(fitx)

plot(x,y,xlim=c(0,5),ylim=c(0,65)) #plot the points (x,y)

beta0 <- fitx$coef[1]

beta1 <- fitx$coef[2]

fn <- function(x) n*exp(beta0+beta1*x)/(1+exp(beta0+beta1*x))

par(new=T)

curve(fn,0,5,ylim=c(0,60)) # plot the logistic regression curve

3. Bootstrap采样

# bootstrap

# Application: 随机采样,获取最大eigenvalue占所有eigenvalue和之比,并画图显示distribution

dat = matrix(rnorm(100*5),100,5)

no.samples = 200 #sample 200 times

# theta = matrix(rep(0,no.samples*5),no.samples,5)

theta =rep(0,no.samples*5)

for (i in 1:no.samples)

{

j = sample(1:100,100,replace = TRUE)#get 100 samples each time

datrnd = dat[j,]#select one row each time

lambda = princomp(datrnd)$sdev^2#get eigenvalues

# theta[i,] = lambda

theta[i] = lambda[1]/sum(lambda)#plot the ratio of the biggest eigenvalue

}

# hist(theta[1,]) #plot the histogram of the first(biggest) eigenvalue

hist(theta)#plot the percentage distribution of the biggest eigenvalue

sd(theta)#standard deviation of theta

#上面注释掉的语句,可以全部去掉注释并将其下一条语句注释掉,完成画最大eigenvalue分布的功能

4. ANOVA方差分析

#Application:判断一个自变量是否有影响 (假设我们喂3种维他命给3头猪,想看喂维他命有没有用)

#

y = rnorm(9)#weight gain by pig(Yij, i is the treatment, j is the pig_id), 一般由用户自行输入

#y = matrix(c(1,10,1,2,10,2,1,9,1),9,1)

Treatment <- factor(c(1,2,3,1,2,3,1,2,3)) #each {1,2,3} is a group

mod = lm(y~Treatment) #linear regression

print(anova(mod))

#解释:Df(degree of freedom)

#Sum Sq: deviance (within groups, and residuals) 总偏差和

# Mean Sq: variance (within groups, and residuals) 平均方差和

# compare the contribution given by Treatment and Residual

#F value: Mean Sq(Treatment)/Mean Sq(Residuals)

#Pr(>F): p-value. 根据p-value决定是否接受Hypothesis H0:多个样本总体均数相等(检验水准为0.05)

qqnorm(mod$residual) #plot the residual approximated by mod

#如果qqnorm of residual像一条直线,说明residual符合正态分布,也就是说Treatment带来的contribution很小,也就是说Treatment无法带来收益(多喂维他命少喂维他命没区别)

如下面两图分别是

(左)用 y = matrix(c(1,10,1,2,10,2,1,9,1),9,1)和

(右)y = rnorm(9)

的结果。可见如果给定猪吃维他命2后体重特别突出的数据结果后,qq图种residual不在是一条直线,换句话说residual不再符合正态分布,i.e., 维他命对猪的体重有影响。

R语言中的多元方差分析1、当因变量(结果变量)不止一个时,可用多元方差分析(MANOVA)对它们同时进行分析。library(MASS)attach(UScereal)y <- cbind(calories, fat, sugars)aggregate(y, by = list(shelf), FUN = mean)Group.1 calories fatsugars1 1 119.4774 0.6621338 6.2954932 2 129.8162 1.3413488 12.5076703 3 180.1466 1.9449071 10.856821cov(y)calories fat sugarscalories 3895.24210 60.674383 180.380317fat60.67438 2.713399 3.995474sugars180.38032 3.995474 34.050018fit <- manova(y ~ shelf)summary(fit)Df Pillai approx F num Df den Df Pr(>F) shelf 1 0.195944.955 3 61 0.00383 **Residuals 63 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1summary.aov(fit)Response calories :Df Sum Sq Mean Sq F valuePr(>F)shelf1 45313 45313 13.995 0.0003983 ***Residuals 63 2039823238 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Response fat :Df Sum Sq Mean Sq F value Pr(>F) shelf1 18.421 18.4214 7.476 0.008108 **Residuals 63 155.236 2.4641---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Response sugars :Df Sum Sq Mean Sq F value Pr(>F) shelf1 183.34 183.34 5.787 0.01909 *Residuals 63 1995.87 31.68 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 12、评估假设检验单因素多元方差分析有两个前提假设,一个是多元正态性,一个是方差—协方差矩阵同质性。(1)多元正态性第一个假设即指因变量组合成的向量服从一个多元正态分布。可以用Q-Q图来检验该假设条件。center <- colMeans(y)n <- nrow(y)p <- ncol(y)cov <- cov(y)d <- mahalanobis(y, center, cov)coord <- qqplot(qchisq(ppoints(n), df = p), d, main = "QQ Plot Assessing Multivariate Normality", ylab = "Mahalanobis D2")abline(a = 0, b = 1)identify(coord$x, coord$y, labels = row.names(UScereal))如果所有的点都在直线上,则满足多元正太性。2、方差—协方差矩阵同质性即指各组的协方差矩阵相同,通常可用Box’s M检验来评估该假设3、检测多元离群点library(mvoutlier)outliers <- aq.plot(y)outliers