R语言学习笔记3_探索性/描述性数据分析
目錄
- 三、探索性/描述性數據分析
- 3.1 直方圖與密度函數的估計
- 3.1.1 直方圖
- 3.1.2 核密度估計
 
- 3.2 單組數據的描述性統計分析
- 3.2.1 單組數據的圖形描述
- 直方圖 hist( )
- 莖葉圖 stem( )
- 箱線圖/框須圖 boxplot( )
- 正態性檢驗
 
- 3.2.2 單組數據的描述性統計
- 總體描述 **summary( )**
- 五數及樣本分位數概括
- 離差的概括
- 樣本偏度系數和峰度系數
- basicStats( )
 
 
- 3.3 多組數據的描述性統計分析
- 3.3.1 兩組數據的圖形概括
- 散點圖
- 等高線圖 contour( )
- 三維透視圖 persp( )
- 數據的變換
 
- 3.3.2 多組數據的圖形描述
- 散點圖 pairs( ) plot( )
- 矩陣圖 matplot( )
- 箱線圖 boxplot( )
 
- 3.3.3 多組數據的描述性統計
- 標準差sd( )與協方差var( )的計算
- 相關系數的計算 cor( )
 
- 3.3.4 分組數據的圖形概括
- 使用條件散點圖 coplot(formula, data, ... )
- 使用直方圖 hists( ) histogram( )
- 使用箱線圖 boxplot( )
- 使用條形圖 stripchart(x, method='overplot', ...)
- 使用密度曲線 densityplot( )
 
 
- 3.4 分類數據的描述性統計分析
- 3.4.1 列聯表的制作
- 由分類數據構造列聯表
- 由原始數據構造列聯表
- 獲得邊際列表 margin.table( )
- 頻率列聯表 prop.table( )
 
- 3.4.2 列聯表的圖形描述
- 使用條形圖
- 使用點圖 dotchart( )
 
 
 
三、探索性/描述性數據分析
3.1 直方圖與密度函數的估計
3.1.1 直方圖
hist(x,breaks='Sturges', #取向量,用于指明直方圖區間的分割位置;#取整數,用于指定直方圖的小區間數freq = NULL, #取T表示使用頻數畫直方圖,F表示使用頻率畫直方圖probability = !freq, col = NULL, #顏色main = paste("Histogram of",xname)), #主標題xlim = range(breaks),ylim=NULL, #軸的上下限 xlab = xname,ylab, #軸標簽axes = TRUE, #T:繪制軸與邊框nclass = NULL)3.1.2 核密度估計
用 density( ) 得到樣本的核密度估計值,再用 lines( ) 得到密度估計的曲線
density(x,bw = "nrd0", #指定核密度估計的窗寬kernel = c("gaussian","epanechnikov","rectangular","triangular","biweight","cosine","optcosine"),n = 512, #等間隔的核密度估計點數from,to) #需要計算核密度估計的左右端點3.2 單組數據的描述性統計分析
3.2.1 單組數據的圖形描述
單組數據的分布可以通過 直方圖、莖葉圖以及箱線圖 考查
例:程序包DAAG中有內嵌數據集“possum”,它包括了從維多利亞南部到皇后區的七個地區的104只負鼠(possum)的年齡、尾巴長度、總長度等9個特征值,我們僅考慮43只雌性負鼠的特征值,建立子集fpossum,考察雌性負鼠的總長度的頻率分布。
直方圖 hist( )
> library(DAAG) #連接程序包 > data(possum) #連接數據集 > fpossum <- possum[sex=="f",] > par(mfrow=c(1,2)) #設置圖排列方式 > attach(fpossum) > hist(totlngth,breaks = 72.5+(0:5)*5,ylim = c(0,22),xlab="total length",main="A:Breaks at 72.5,77.5,...") > hist(totlngth,breaks = 75+(0:5)*5,ylim = c(0,22),xlab="total length",main="A:Breaks at 75,80,...")
 兩個圖選擇的區間端點不同:可以看出,左邊不對稱,而右邊顯示該分布是對稱的。
莖葉圖 stem( )
> stem(fpossum$totlngth)The decimal point is at the |74 | 076 | 78 | 80 | 0582 | 050084 | 0500586 | 0550588 | 000550000555590 | 555005592 | 00094 | 0596 | 5箱線圖/框須圖 boxplot( )
boxplot(formula,data=NULL,…,subset,na.action=NULL)
 formula指明作圖規則(y~grp表示數值變量y根據因子grp分類),data說明數據的來源
 箱子中的五根橫線分別對應:最小值、上四分位數,中位數,下四分位數和最大值。
正態性檢驗
1)使用QQ圖
> qqnorm(fpossum$totlngth) > qqline(fpossum$totlngth,col='red')
 上圖表明,數據與正態性略有差異,特別在圖形的中部。
 2)與正態密度函數比較
 上圖表明數據totlngth與正態性也略有差異,進一步需要使用統計量進行正態性檢驗。
 3)使用經驗分布函數
3.2.2 單組數據的描述性統計
總體描述 summary( )
可以計算出但組數據的均值和五數(最小值,上四分位數,中位數,下四分位數,最大值)
> summary(totlngth)Min. 1st Qu. Median Mean 3rd Qu. Max. 75.00 85.25 88.50 87.91 90.50 96.50五數及樣本分位數概括
計算五數 > fivenum(totlngth) [1] 75.00 85.25 88.50 90.50 96.50 計算分位數 > quantile(totlngth)0% 25% 50% 75% 100% 75.00 85.25 88.50 90.50 96.50 計算指定的分位數 > quantile(totlngth,prob=c(0.1,0.25,0.5))10% 25% 50% 82.60 85.25 88.50 中位數 > median(totlngth) [1] 88.5 最大值 > max(totlngth) [1] 96.5 最小值 > min(totlngth) [1] 75 均值 > mean(totlngth) [1] 87.90698離差的概括
絕對離差 mad() 在R中的定義為:1.4826*median(abs(x-median(x)))
極值 > max(totlngth)-min(totlngth) [1] 21.5 四分位極值 > IQR(totlngth) [1] 5.25 標準差 > sd(totlngth) [1] 4.182241 方差 > sd(totlngth)^2 [1] 17.49114 > var(totlngth) [1] 17.49114 絕對離差 > mad(totlngth) [1] 3.7065樣本偏度系數和峰度系數
偏度系數 skewness( )
| 偏度系數 = 0 | 關于均值對稱 | 
| 偏度系數 < 0 | 負偏(左偏) | 
峰度系數 kurtosis( )
| 峰度系數 = 0 | 與高斯分布相當 | 
| 峰度系數 < 0 | 低峰度,比高斯分布更平坦 | 
basicStats( )
> basicStats(totlngth)totlngth nobs 43.000000 #觀測總數 NAs 0.000000 Minimum 75.000000 Maximum 96.500000 1. Quartile 85.250000 3. Quartile 90.500000 Mean 87.906977 Median 88.500000 Sum 3780.000000 SE Mean 0.637786 LCL Mean 86.619873 UCL Mean 89.194081 Variance 17.491141 Stdev 4.182241 Skewness -0.548380 Kurtosis 0.6170083.3 多組數據的描述性統計分析
3.3.1 兩組數據的圖形概括
例:在程序包DAAG中有數據集cars,估計速度(speed)和終止距離(dist)之間的關系
散點圖
> library(DAAG) > data(cars) > attach(cars) > plot(dist~speed,xlab='speed',ylab='stopping distance') > lines(lowess(speed,dist),lwd=2) # 局部加權回歸(Lowess) #在軸上標明數據的具體位置 > rug(side=2,jitter(dist,20)) > rug(side=1,jitter(speed,5)) #在數軸兩邊加上單變量的箱線圖
 上圖表明二者基本呈線性相依關系。
 lowess(x,y=NULL,f=2/3,iter=3,delta=0.01*diff(range(xy$x[o]))) 適用于二維
 loess( ) 適用于多維
等高線圖 contour( )
有時數據太多太集中,散點圖上的信息不容易看出來。一般,先使用MASS程序包中的二維核密度估計函數kde2d()來估計二維數據的密度函數,再利用函數contour()畫出密度的等高線圖。
> library(MASS) > z <- kde2d(x,y) > contour(z,col ='red',drawlabels = F)三維透視圖 persp( )
數據的變換
當直接用原數據得不到有意義的圖形時,可以對數值進行變換,得到有意義的圖形。最常用的是:對數變換、倒數變換、指數變換和Box-Cox變換。
> library(MASS) > data("Animals") > attach(Animals) > par(mfrow=c(1,2)) > plot(brain~body) > title(main='原始數據') > plot(log(brain)~log(body)) > title(main='取對數后')
 左側的散點圖沒有價值,而從右側的散點圖可以看出兩組數據在取對數后呈現明顯的線性相依關系。
3.3.2 多組數據的圖形描述
例子:產生五個樣本容量為10的標準正態分布的樣本,取絕對值后生成數據框d
>n<-10 >d<- data.frame(y1=abs(rnorm(n)),y2=abs(rnorm(n)),y3=abs(rnorm(n)),y4=abs(rnorm(n)),y5=abs(rnorm(n)))散點圖 pairs( ) plot( )
多組數據的散點圖就是不同變量的散點圖像矩陣一樣放在一起。
> plot(d) # 或 pairs(d)矩陣圖 matplot( )
與散點圖矩陣的區別在于將各個散點圖放在了同一個作圖區域中。
> matplot(d,type = 'l')箱線圖 boxplot( )
3.3.3 多組數據的描述性統計
例子:程序包datasets中數據框state.x77描述了美國50個州的人口數、人均收入、人均壽命、一年中有霧的天數等情況。
> state.x77Population Income Illiteracy Life Exp Murder HS Grad Frost Area Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708 Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432 Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417 Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945 California 21198 5114 1.1 71.71 10.3 62.6 20 156361 ...... Wisconsin 4589 4468 0.7 72.48 3.0 54.5 149 54464 Wyoming 376 4566 0.6 70.29 6.9 62.9 173 972031)使用函數 summary( ) 概括state.x77
> summary(state.x77)Population Income Illiteracy Life Exp Murder HS Grad Min. : 365 Min. :3098 Min. :0.500 Min. :67.96 Min. : 1.400 Min. :37.80 1st Qu.: 1080 1st Qu.:3993 1st Qu.:0.625 1st Qu.:70.12 1st Qu.: 4.350 1st Qu.:48.05 Median : 2838 Median :4519 Median :0.950 Median :70.67 Median : 6.850 Median :53.25 Mean : 4246 Mean :4436 Mean :1.170 Mean :70.88 Mean : 7.378 Mean :53.11 3rd Qu.: 4968 3rd Qu.:4814 3rd Qu.:1.575 3rd Qu.:71.89 3rd Qu.:10.675 3rd Qu.:59.15 Max. :21198 Max. :6315 Max. :2.800 Max. :73.60 Max. :15.100 Max. :67.30 Frost Area Min. : 0.00 Min. : 1049 1st Qu.: 66.25 1st Qu.: 36985 Median :114.50 Median : 54277 Mean :104.46 Mean : 70736 3rd Qu.:139.75 3rd Qu.: 81163 Max. :188.00 Max. :5664322)使用分組概括函數 aggregate(x,by,FUN,…) ,其中,x是數據框,by指定分組變量 ,fun是用于計算的統計函數
統計不同地區(Northeast, South, North Central, West)的均值。 > aggregate(state.x77,list(Region = state.region),mean)Region Population Income Illiteracy Life Exp Murder HS Grad Frost Area 1 Northeast 5495.111 4570.222 1.000000 71.26444 4.722222 53.96667 132.7778 18141.00 2 South 4208.125 4011.938 1.737500 69.70625 10.581250 44.34375 64.6250 54605.12 3 North Central 4803.000 4611.083 0.700000 71.76667 5.275000 54.51667 138.8333 62652.00 4 West 2915.308 4702.615 1.023077 71.23462 7.215385 62.00000 102.1538 134463.00 統計一年中霧天超過130的地區的均值 > aggregate(state.x77,list(Region = state.region,Cold=state.x77[,"Frost"]<130),mean)Region Cold Population Income Illiteracy Life Exp Murder HS Grad Frost Area 1 Northeast FALSE 1360.5000 4307.500 0.7750000 71.43500 3.650000 56.35000 160.5000 13519.00 2 North Central FALSE 2372.1667 4588.833 0.6166667 72.57667 2.266667 55.66667 157.6667 68567.50 3 West FALSE 970.1667 4880.500 0.7500000 70.69167 7.666667 64.20000 161.8333 184162.17 4 Northeast TRUE 8802.8000 4780.400 1.1800000 71.12800 5.580000 52.06000 110.6000 21838.60 5 South TRUE 4208.1250 4011.938 1.7375000 69.70625 10.581250 44.34375 64.6250 54605.12 6 North Central TRUE 7233.8333 4633.333 0.7833333 70.95667 8.283333 53.36667 120.0000 56736.50 7 West TRUE 4582.5714 4550.143 1.2571429 71.70000 6.828571 60.11429 51.0000 91863.71 # Cold=T,表示該地區一年有霧的天數超過130天標準差sd( )與協方差var( )的計算
> var(state.x77)Population Income Illiteracy Life Exp Murder HS Grad Population 19931683.7588 571229.7796 292.8679592 -4.078425e+02 5663.523714 -3551.509551 Income 571229.7796 377573.3061 -163.7020408 2.806632e+02 -521.894286 3076.768980 Illiteracy 292.8680 -163.7020 0.3715306 -4.815122e-01 1.581776 -3.235469 Life Exp -407.8425 280.6632 -0.4815122 1.802020e+00 -3.869480 6.312685 Murder 5663.5237 -521.8943 1.5817755 -3.869480e+00 13.627465 -14.549616 HS Grad -3551.5096 3076.7690 -3.2354694 6.312685e+00 -14.549616 65.237894 Frost -77081.9727 7227.6041 -21.2900000 1.828678e+01 -103.406000 153.992163 Area 8587916.9494 19049013.7510 4018.3371429 -1.229410e+04 71940.429959 229873.192816Frost Area Population -77081.97265 8.587917e+06 Income 7227.60408 1.904901e+07 Illiteracy -21.29000 4.018337e+03 Life Exp 18.28678 -1.229410e+04 Murder -103.40600 7.194043e+04 HS Grad 153.99216 2.298732e+05 Frost 2702.00857 2.627039e+05 Area 262703.89306 7.280748e+09> options(digits=3) #設置小數位 > aggregate(state.x77,list(Region = state.region),sd)Region Population Income Illiteracy Life Exp Murder HS Grad Frost Area 1 Northeast 6080 559 0.278 0.744 2.67 3.93 30.9 18076 2 South 2780 605 0.552 1.022 2.63 5.74 31.3 57965 3 North Central 3703 283 0.141 1.037 3.57 3.62 23.9 14967 4 West 5579 664 0.608 1.352 2.68 3.50 68.9 134982相關系數的計算 cor( )
cor(x, y = NULL, use = ‘all.obs’, method = c(‘pearson’,‘kendall’,‘spearman’))
> x <- c(44.4,45.9,46,46.5,46.7,47,48.7,49.2,60.1) > v <- c(2.6,10.1,11.5,30,32.6,50,55.2,85.8,86.8) > cor(x,v) [1] 0.769 > cor(x,v,method = 'spearman') [1] 1 > cor(x,v,method = 'kendall') [1] 1 > plot(x,v)
 從散點圖中可以看出,x與v的線性相關系數收到右上角一個極端值的影響變小了 。因此在計算相關性度量的時候,要考慮計算哪種相關系數更有意義。
3.3.4 分組數據的圖形概括
例:程序包DAAG中cuckoos數據集。杜鵑把蛋下在其他種類鳥的鳥巢中,這些鳥會幫它們孵化,我們希望了解在不同類的鳥巢中杜鵑蛋的長度。
> data("cuckoos") > cuckooslength breadth species id 1 21.7 16.1 meadow.pipit 21 2 22.6 17.0 meadow.pipit 22 3 20.9 16.2 meadow.pipit 23 ...... 119 21.2 16.0 wren 237 120 21.0 16.0 wren 238 > attach(cuckoos)使用條件散點圖 coplot(formula, data, … )
| 對于兩個因子變量a b | coplot(y~x | a*b) | 
使用直方圖 hists( ) histogram( )
1)直方組圖hists()
#直方組圖定義 hists<- function(x,y,...){y<- factor(y)n<- length(levels(y))op<- par(mfcol=c(n,1),mar=c(2,4,1,1))b<- hist(x,...,plot=F)$breaksfor (l in levels(y)){hist(x[y==l],breaks=b,probability = T,ylim=c(0,1.0),main=" ",ylab=l,col='lightblue',xlab="",...)points(density(x[y==l]),type='l',lwd=3,col='red')}par(op) }> hists(length,species)
 2)用lattice包中的histogram( )
使用箱線圖 boxplot( )
> boxplot(length~species,horizontal = T) # T:橫向放置箱子使用條形圖 stripchart(x, method=‘overplot’, …)
method說明數據重復的時候該如何放置,overplot是重疊放置,stack是把數據壘起來,jitter是散放在數據的周圍。
> stripchart(length~species,method='jitter') > stripchart(length~species,method='stack')使用密度曲線 densityplot( )
> densityplot(~length|species)3.4 分類數據的描述性統計分析
3.4.1 列聯表的制作
由分類數據構造列聯表
例:為考查眼睛顏色(Eye)與頭發顏色(Hair)之間的關系,收集了下面一組數據:
| Hair | Brown | Blue | Hazel | Green | 
| Black | 68 | 20 | 15 | 5 | 
| Brown | 119 | 84 | 54 | 29 | 
| Red | 26 | 17 | 14 | 14 | 
| Blond | 7 | 94 | 10 | 16 | 
由原始數據構造列聯表
R中可以使用函數table( ), xtabs( ), ftable( )由原始數據構造列聯表。
 table(factor1,factor2,…)
例:數據包ISwR中的數據集juul中含有三個分類變量:sex, tanner, menarche
> table(sex) > table(sex,manarche) > table(menarche,tanner)獲得邊際列表 margin.table( )
> margin.table(Eye.Hair,1) #按行 Black Brown Red Blond 108 286 71 127 > margin.table(Eye.Hair,2) #按列 Brown Blue Hazel Green 220 215 93 64頻率列聯表 prop.table( )
(相對)頻率列聯表 > round(prop.table(Eye.Hair,1),digits=2)Brown Blue Hazel Green Black 0.63 0.19 0.14 0.05 Brown 0.42 0.29 0.19 0.10 Red 0.37 0.24 0.20 0.20 Blond 0.06 0.74 0.08 0.13 全局相對頻率列聯表 > round(Eye.Hair/sum(Eye.Hair),digits = 2)Brown Blue Hazel Green Black 0.11 0.03 0.03 0.01 Brown 0.20 0.14 0.09 0.05 Red 0.04 0.03 0.02 0.02 Blond 0.01 0.16 0.02 0.03 #round() 保留小數點指定位數 digits 有效數字3.4.2 列聯表的圖形描述
使用條形圖
> data("HairEyeColor") > a<- as.table(apply(HairEyeColor,c(1,2),sum)) #apply(矩陣,按x,y,求和) > aEye Hair Brown Blue Hazel GreenBlack 68 20 15 5Brown 119 84 54 29Red 26 17 14 14Blond 7 94 10 16 > barplot(a,legend.text = attr(a,'dimnames')$Hair) > barplot(a,besid=TRUE,legend.text = attr(a,'dimnames')$Hair)使用點圖 dotchart( )
> dotchart(a)總結
以上是生活随笔為你收集整理的R语言学习笔记3_探索性/描述性数据分析的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 【门禁小知识】常用门禁分类及连接图
- 下一篇: Linux之shell脚本正则表达式
