R语言基本数据分析

Python016

R语言基本数据分析,第1张

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读取的时候把它默认为是因子类型了,用as.numeric()函数也没有用。

     问题解决基本思想就是把百分数按照字符处理,首先将“%”与数字分离,然后再将数除以100,就可以化成小数了。

year_ratio_pri <- cbind(year_ratio_pri[,1],

  data.frame(lapply(year_ratio_pri[,2:4],  

                  function(x) as.numeric(gsub("\\%", "", x))/100)) )

暂时我没用过,思路绝对没问题

数据准备

1 基础图形绘制

2 禁用坐标轴

禁用全部坐标轴

禁用坐标轴但保留边框

禁用部分坐标轴

3 坐标轴参数设置

函数:axis(side, at = NULL, labels = TRUE, tick = TRUE, line = NA, pos = NA, outer = FALSE, font = NA, lty = "solid", lwd = 1, lwd.ticks = lwd, col = NULL, col.ticks = NULL, hadj = NA, padj = NA, gap.axis = NA, ...)

side表示坐标轴位置,取值1、2、3、4分别代表下、左、上、右;

at表示需要添加刻度的数值,默认会根据变量的取值范围计算几个合适的刻度,也可以手工指定;

labels表示刻度标签,指定在刻度上需要标记的内容,默认就是刻度对应的值;

tick是逻辑变量,取TRUE表示显示坐标轴和刻度线,取FALSE时,坐标轴线和刻度线不画出;

line表示坐标轴线位置与图像边框的距离,取负数时会画在图像边框以内;

pos 表示轴线所在的位置; line.outer取TRUE时,坐标轴将画在画布边缘处; font.axis表示坐标轴刻度值的字体,font=1表示正体,2表示黑体,3表示斜体,4表示黑斜体。

lty表示线型,用在axis函数中表示坐标轴线型;

lwd表示线的粗细,用在axis函数中表示坐标轴线粗细;

lwd.ticks表示刻度线粗细。

col表示图的颜色,用在axis函数中表示坐标轴线和坐标刻度线的颜色;

col.axis表示坐标轴刻度值的颜色;

col.ticks表示坐标轴刻度线的颜色;

hadj指将刻度值沿平行坐标轴方向调整的距离;

padj指将刻度值沿垂直坐标轴方向调整的距离;

las表示坐标刻度值文字方向,las=0表示文字方向与坐标轴平行,1表示始终为水平方向,2表示与坐标轴垂直,3表示终为垂直方向。

tck表示刻度线长度。

4 次要刻度线

minor.tick(nx=n,ny=n,tick.ration=n)

nx和ny分别指定了X轴和Y轴每两条主刻度线之间通过次要刻度线划分得到的区间个数。 tick.ratio表示次要刻度线相对于主刻度线的大小比例。

参考资料:

《R语言实战》(中文版),人民邮电出版社,2013.

R语言作图:坐标轴设置, https://blog.csdn.net/weixin_40628687/article/details/79254791

R语言低级绘图函数-axis, https://www.cnblogs.com/xudongliang/p/6762618.html