R語言 基本資料分析

2021-06-20 09:58:16 字數 2595 閱讀 5201

本文基於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 y

n z

b fitx

print(fitx)

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

beta0

beta1

fn par(new=t)

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

3. bootstrap取樣

# bootstrap

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)

# 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方差分析

# 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

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 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., 維他命對豬的體重有影響。

關注資料統計分析,歡迎一起討論。微博 rachel____zhang

R語言 資料分析

二 大資料分析 三 資料分析常用工具 資料分析是指用適當的統計方法對收集來的大量第一手資料和第二手資料進行分析,以求最大化地開發資料資料的功能,發揮資料的作用。資料分析是為了驗證假設的問題,需要提供必要的資料驗證。分析模型構建完成後,需要利用測試資料驗證模型的正確性。資料分析是為了挖掘更多的問題,並...

R語言與資料分析 R語言的基本原理

1 r 是一種解釋型語言,這就意味著輸入的命令能夠直接被執行,而不需要像一些語言首先構成乙個 完整的程式形式 2 合法的r函式總是帶有圓括號的形式,即使括號內沒有內容 ls 帶有圓括號 也是 與物件作為區別的乙個標誌 3 當r執行時,所有變數,資料,函式及結果都以物件 objects 的形式存在計算...

R語言 TCGA資料分析一

我最近在做tcga資料分析,在處理中遇到的問題及其收穫。主要包括 涉及到的函式有 小寫 大寫 單一的區域性匹配 多個全域性匹配 保留固定長度的字元在ranseqgene中case id 為大寫的,而clincial中為小寫的。需要對case id 做轉換。方案一 大寫變小寫tolower colna...