当前位置:新励学网 > 秒知问答 > R语言基本数据分析

R语言基本数据分析

发表时间:2024-07-21 04:49:08 来源:网友投稿

R语言基本数据分析

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

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

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

#basicplot

boxplot(x)

qqplot(x,y)

2.线性拟合

#linearregression

n=10

x1=rnorm(n)#variable1

x2=rnorm(n)#variable2

y=rnorm(n)*3

mod=lm(y~x1+x2)

model.matrix(mod)#erectthematrixofmod

plot(mod)#plotresidualandfittedofthesolution,Q-Qplotandcookdistance

summary(mod)#getthestatisticinformationofthemodel

hatvalues(mod)#veryimportant,forabnormalsampledetection

3.逻辑回归

#logisticregression

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

y<-c(0,9,21,47,60,63)#thenumberofsuccesses

n<-70#thenumberoftrails

z<-n-y#thenumberoffailures

b<-cbind(y,z)#columnbind

fitx<-glm(b~x,family=binomial)#aparticulartypeofgeneralizedlinearmodel

print(fitx)

plot(x,y,xlim=c(0,5),ylim=c(0,65))#plotthepoints(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))#plotthelogisticregressioncurve

3.Bootstrap采样

#bootstrap

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

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

no.samples=200#sample200times

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

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

for(iin1:no.samples)

{

j=sample(1:100,100,replace=TRUE)#get100sampleseachtime

datrnd=dat[j,];#selectoneroweachtime

lambda=princomp(datrnd)$sdev^2;#geteigenvalues

#theta[i,]=lambda;

theta[i]=lambda[1]/sum(lambda);#plottheratioofthebiggesteigenvalue

}

#hist(theta[1,])#plotthehistogramofthefirst(biggest)eigenvalue

hist(theta);#plotthepercentagedistributionofthebiggesteigenvalue

sd(theta)#standarddeviationoftheta

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

4.ANOVA方差分析

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

#

y=rnorm(9);#weightgainbypig(Yij,iisthetreatment,jisthepig_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}isagroup

mod=lm(y~Treatment)#linearregression

print(anova(mod))

#解释:Df(degreeoffreedom)

#SumSq:deviance(withingroups,andresiduals)总偏差和

#MeanSq:variance(withingroups,andresiduals)平均方差和

#comparethecontributiongivenbyTreatmentandResidual

#Fvalue:MeanSq(Treatment)/MeanSq(Residuals)

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

qqnorm(mod$residual)#plottheresidualapproximatedbymod

#如果qqnormofresidual像一条直线,说明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.,维他命对猪的体重有影响。

免责声明:本站发布的教育资讯(图片、视频和文字)以本站原创、转载和分享为主,文章观点不代表本网站立场。

如果本文侵犯了您的权益,请联系底部站长邮箱进行举报反馈,一经查实,我们将在第一时间处理,感谢您对本站的关注!