99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀R語(yǔ)言與數(shù)據(jù)的預(yù)處理
R語(yǔ)言與數(shù)據(jù)的預(yù)處理
2016-10-08
收藏

R語(yǔ)言與數(shù)據(jù)的預(yù)處理

在面對(duì)大規(guī)模數(shù)據(jù)時(shí),對(duì)數(shù)據(jù)預(yù)處理,獲取基本信息是十分必要的。今天分享的就是數(shù)據(jù)預(yù)處理的一些東西。

一、獲取重要數(shù)據(jù)

在導(dǎo)入大規(guī)模數(shù)據(jù)時(shí),我們通常需要知道數(shù)據(jù)中的關(guān)鍵內(nèi)容:最值,均值,離差,分位數(shù),原點(diǎn)矩,離差,方差等。在R中常用的函數(shù)與作用整理如下:

統(tǒng)計(jì)函數(shù)
作用
Max
返回?cái)?shù)據(jù)的最大值
Min
返回?cái)?shù)據(jù)的最小值
Which.max
返回最大值的下標(biāo)
Which.min
返回最小值的下標(biāo)
Mean
求均值
Median
求中位數(shù)
mad
求離差
Var
求方差(總體方差)
Sd
求標(biāo)準(zhǔn)差
Range
返回【最小值,最大值】
Quantile
求分位數(shù)
Summary
返回五數(shù)概括與均值
Finenum
五數(shù)概括(最值,上下四分位數(shù),中位數(shù))
Sort
排序(默認(rèn)升序,decreasing=T時(shí)為降序)
Order
排序(默認(rèn)升序,decreasing=T時(shí)為降序)
Sum
求和
length
求數(shù)據(jù)個(gè)數(shù)
emm
Actuar包中求k階原點(diǎn)矩
skewness
Fbasic包中求偏度
kurtosis
Fbasics包中求峰度

注:對(duì)象為分組數(shù)據(jù),矩陣時(shí)返回的不是整體的方差,均值,而是每一列(組)的方差均值其余變量類似。

二、直方圖與頻數(shù)統(tǒng)計(jì)

對(duì)于數(shù)據(jù)分布的認(rèn)識(shí),在大規(guī)模時(shí)有必要使用直方圖。在R語(yǔ)言中,直方圖的函數(shù)調(diào)用為:

hist(x, breaks = "Sturges",
freq = NULL, probability = !freq,
include.lowest = TRUE, right = TRUE,
density = NULL, angle = 45, col = NULL, border = NULL,
main= paste("Histogram of" , xname),
xlim = range(breaks), ylim = NULL,
xlab = xname, ylab,
axes = TRUE, plot = TRUE, labels = FALSE,
nclass = NULL, warn.unused = TRUE, ...)

這里值得一提的是,分組參數(shù)breaks默認(rèn)使用史特吉斯(Sturges)公式,根據(jù)測(cè)定數(shù)n 來(lái)計(jì)算組距數(shù)k,公式為:k=1+3.32 logn。當(dāng)然也可以自己設(shè)定一個(gè)數(shù)組來(lái)決定分組。(舉例參見(jiàn)《R語(yǔ)言繪圖學(xué)習(xí)筆記》)

說(shuō)完頻率分布直方圖,我們還有頻率分布直方表。對(duì)于數(shù)據(jù)的統(tǒng)計(jì),函數(shù)table可以統(tǒng)計(jì)出數(shù)據(jù)中完全相同的數(shù)據(jù)個(gè)數(shù)。例如對(duì)《全宋詞》中暴力拆解(兩個(gè)相鄰字算一詞)詞語(yǔ)使用數(shù)目的統(tǒng)計(jì)程序如下:

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>l=scan(“Ci.txt”,”character”,sep=”\n”);

    l.len=nchar(l);

    ci=l;

    sentences=strsplit(ci,”,|。|!|?|、”);# 句子用標(biāo)點(diǎn)符號(hào)分割。

    sentences=unlist(sentences);

    sentences=sentences[sentences!=””];

    s.len=nchar(sentences);#單句太長(zhǎng)了說(shuō)明有可能是錯(cuò)誤的字符,去除掉。

    sentences=sentences[s.len<=10];

    s.len=nchar(sentences);

    splitwords=function(x,x.len)substring(x,1:(x.len-1),2:x.len);

    words=mapply(splitwords,sentences,s.len,SIMPLIFY=TRUE,USE.NAMES=FALSE);

    words=unlist(words);

    words.freq=table(words);#詞頻統(tǒng)計(jì)

    words.freq=sort(words.freq,decreasing=TRUE);

    data.frame(Word=names(words.freq[1:100]),Freq=as.integer(words.freq[1:100]));</span>

而對(duì)于一堆數(shù),我們按區(qū)間做的時(shí)候,就還需要函數(shù)cut.調(diào)用格式如下:

cut(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3, ordered_result = FALSE, ...)

舉一個(gè)具體例子,某一款保險(xiǎn)產(chǎn)品,假設(shè)保單到達(dá)的速率為10張/天,理賠發(fā)生的速率為 1次/天。假設(shè)每張保單價(jià)格c=120,理賠額服從參數(shù)為v=1/1000 (以c*lambda1=1.2*lambda2/v設(shè)定)的指數(shù)分布。設(shè)定初始u=3000時(shí),計(jì)算到第1000天為止發(fā)生破產(chǎn)的概率。(案例摘自《復(fù) 合泊松過(guò)程模型的推廣和在R語(yǔ)言環(huán)境下的隨機(jī)模擬》 )

破產(chǎn)過(guò)程的R代碼如下:

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>pois.proc= function(T, lambda){

    S = 0

    I =rpois(1, lambda*T) #產(chǎn)生t 泊松分布,這里調(diào)用R 內(nèi)置的泊松函數(shù)避免循環(huán)。

    U =runif(I)

    S =sort(T * U) #排序產(chǎn)生順序統(tǒng)計(jì)量的思想

    list(I= I, S = S)

    }


    broken.proc= function(k, u= 3000, c= 120){

    n =1000  #模擬到時(shí)刻 1000 為止的破產(chǎn)情況

    M =pois.proc(n, 10)

    N =pois.proc(n, 1)

    U = u   #初始盈余

    X = 0

    result=0

    A =sort(c(M$S, N$S))  #M$S和 N$S 是保單和理賠達(dá)到時(shí)刻

    for(iin 1:length(A)){

    if(any(A[i]==N$S)== 0)

    U=U+c

    else {

    X[i] =rexp(1, rate=1/1000)

    U = U -X[i]   #減去這個(gè)隨機(jī)值

    if(U< 0){    #判斷盈余是否小于0(保單到達(dá)的時(shí)候不需要判斷)

    result<-A[i]   #盈余小于 0時(shí),記錄這個(gè)理賠到達(dá)(破產(chǎn))的刻

    break}

    }

    }

    if(U>= 0){   #如果 for循環(huán)沒(méi)有中斷,判最終的盈余其實(shí)肯定非負(fù)

    result= n + 200

    }  #給結(jié)果賦值一個(gè)明顯比模擬時(shí)刻大的數(shù)據(jù),表示未破產(chǎn)

    return(result)   #返回最終結(jié)果

    }

    #根據(jù)這個(gè)破產(chǎn)過(guò)程可以模擬保險(xiǎn)人的頻數(shù)和頻率:

    simulation= function(n=100){ #定義一個(gè)重復(fù)模擬破產(chǎn)過(guò)程的函數(shù)

    t =numeric(n)

    for(iin 1:n){

    t[i] =broken.proc(i)}   #產(chǎn)生 n次破產(chǎn)或者代表未破產(chǎn)的時(shí)刻

    return(t)}

    time=simulation(n= 1200)

    rangetime= time[time!=1200]

    breakratio= length(rangetime)/length(time);

    breakratio

    break.points<-c(0,10,20,30,40,50,100,200,300,400,500,1000,1200)

    table(cut(time,breaks=break.points))

    hist(rangetime,breaks = 50, xlab=’broken time’,xlim = c(0, max(rangetime)),main = ‘Histogramof Broken time’)</span>

用R 語(yǔ)言模擬了1200 次,最終結(jié)果 1200 次中破產(chǎn) 628 次,破產(chǎn)率大概 52.3% 。輸出各階段破產(chǎn)時(shí)刻 頻數(shù)和率結(jié)果如下:


區(qū)間
    

頻數(shù)
    
    
    

(0,10]
    

389
    
    
    

(10,20]
    

89
    
    
    

(20,30]
    

45
    
    
    

(30,40]
    

28
    
    
    

(40,50]
    

16
    
    
    

(50,100]
    

36
    
    
    

(100,200]
    

17
    
    
    

(200,300]
    

6
    
    
    

(300,400]
    

2
    
    
    

(400,500]
    

0
    
    
    

(500,1000]
    

0
    
    
    

(1000,1200]
    

572
    
    
    

對(duì)于一些數(shù)據(jù)我們可能直接錄入的是頻率分布直方表,那么actuar包中提供了一個(gè)有用的數(shù)據(jù)結(jié)構(gòu)grouped.data。調(diào)用格式:

grouped.data(..., right = TRUE, row.names = NULL, check.rows = FALSE,

check.names = TRUE)

運(yùn)用舉例:

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>library(actuar)

    z=rnorm(10000)

    break.points<-c(-Inf,-3,-2,-1,0,1,2,3,Inf)

    tz<-table(cut(z,breaks=break.points))

    tz

    zz<-grouped.data(Group=break.points,freq=as.matrix(tz))

    zz</span>

對(duì)比一下下面的輸出結(jié)果,我們發(fā)現(xiàn)分組數(shù)據(jù)的均值計(jì)算與總體數(shù)據(jù)計(jì)算方法是不一樣的。

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>mean(zz)

    mean(zz[c(2:7),])

    mean(z)</span>

注:函數(shù)elev()可以計(jì)算有限期望值,可以避免mean(zz)不存在的尷尬。

當(dāng)然對(duì)于數(shù)據(jù)的直觀分析R提供的函數(shù)有許多,我們將常見(jiàn)的函數(shù)匯總?cè)缦拢?br />
[plain] view plaincopyprint?

    EDA <- function (x)

      {

        par(mfrow=c(2,2))              # 同時(shí)做4個(gè)圖

        hist(x)                        # 直方圖

        dotchart(x)                    # 點(diǎn)圖

        boxplot(x,horizontal=T)        # 箱式圖

        qqnorm(x);qqline(x)            # 正態(tài)概率圖

        par(mfrow=c(1,1))              # 恢復(fù)單圖

      }

三、正態(tài)檢驗(yàn)與經(jīng)驗(yàn)分布

對(duì)于數(shù)據(jù)的分布估計(jì)經(jīng)驗(yàn)分布是一個(gè)非常好的估計(jì)。在actuar包中函數(shù)ogive給出的實(shí)現(xiàn):

ogive(x, y = NULL, …)

## S3 method for class ‘ogive’

print(x, digits = getOption(“digits”) – 2, …)

## S3 method for class ‘ogive’

summary(object, …)

## S3 method for class ‘ogive’

knots(Fn, …)

## S3 method for class ‘ogive’

plot(x, main = NULL, xlab = “x”, ylab = “F(x)”, …)

還是以上面的例子數(shù)據(jù)zz為例:

ogive(zz)

plot(ogive(zz))

輸出結(jié)果:

Ogive forgrouped data

Call:ogive(zz)

x =  -Inf,     -3,     -2, …,      3,    Inf

F(x) =     0, 0.0011, 0.0229,  …,0.9985,      1

由于大數(shù)定律的存在,很多情況下,正態(tài)性檢驗(yàn)是十分有必要的一個(gè)分布檢驗(yàn),在R中提供的正態(tài)性檢驗(yàn)可以匯總為下面的一個(gè)正態(tài)檢驗(yàn)函數(shù):

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>NormTest<-function(data){

    library(fBasics)

    library(nortest)

    udata<-unique(data)

    result<-list()

    result$D<-dagoTest(data)

    result$jB<-jarqueberaTest(data)

    result$SW<-shapiroTest(data)

    result$lillie<-lillie.test(data)

    result$ad<-ad.test(data)

    result$cvm<-cvm.test(data)

    result$sf<-sf.test(data)

    return(result)

    }</span>

對(duì)于分布的檢驗(yàn)還有卡方檢驗(yàn),柯?tīng)柲缏宸驒z驗(yàn)等,在R中也有實(shí)現(xiàn)函數(shù)chisq.test()等。我們同樣以一個(gè)例子來(lái)說(shuō)明:


解答如下:(結(jié)果以注釋形式標(biāo)明)

[plain] view plaincopyprint?

    <span style=”font-size:18px;”>v<-c(57,203,383,525,532,408,273,139,45,27,16)

    chisq.test(v)#p<0.05,認(rèn)為檢驗(yàn)總體是否與給定的p相同,p缺省表示等可能性檢驗(yàn)

    #驗(yàn)證V的分布是否為poission分布

    x<-0:10

    options(digits=3)

    likely<-function(lamda=3){

    -sum(y*dpois(x,lamda=lamda,log=T))

    }

    library(stats4)

    mle(likely)

    chisq.fit<-function(x,y,r){

    options(digits=4)

    result<-list()

    n<-sum(y)

    prob<-dpois(x,3.87,log=F)

    y<-c(y,0)

    m<-length(y)

    prob<-c(prob,1-sum(prob))

    result$chisq<-sum((y-n*prob)^2/(n*prob))

    result$p.value<-pchisq(result$chisq,m-r-1,lower.tail=F)

    result

    }

    chisq.fit(x,v,1)#p<0.05 拒絕假設(shè)分布</span>

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }