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

熱線電話:13121318867

登錄
首頁精彩閱讀R語言:函數(shù)使用技巧(循環(huán)、if族/for、switch、repeat、ifelse、stopifnot)
R語言:函數(shù)使用技巧(循環(huán)、if族/for、switch、repeat、ifelse、stopifnot)
2017-04-29
收藏

R語言:函數(shù)使用技巧(循環(huán)、if族/for、switch、repeat、ifelse、stopifnot)

1、循環(huán)
[plain] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ##循環(huán)for  
    iris  
    allzl=unique(iris$setosa)  
    for (i in 1:2){  
      pp=iris[iris$setosa==allzl[i],]  
      plot(pp$Sepal.Length~pp$Sepal.Width)  
    } 
for循環(huán)中,需要將數(shù)值組合起來,如果數(shù)據(jù)整齊可以用matrix;如果不整齊,用list,不等長(zhǎng)合并的時(shí)候,rbind.fill函數(shù)可以很好將數(shù)據(jù)進(jìn)行合并,并且補(bǔ)齊沒有匹配到的缺失值為NA。
案 例
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    temp<-matrix(data = NA,181,31)  
    for (i in 1:31){  
      temp[,i]<-filter(data[i]/7, rep(1, 7))  
      }  
    yatmdata<-data.frame(temp) 
代碼利用matrix先定義一個(gè)181*31的空值矩陣,然后往里面灌數(shù)字。
2、switch分支語句
[plain] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ##switch分支語句  
    switch(1,mean(1:10),rnorm(4))  #執(zhí)行mean(1:10)  
    switch(2,mean(1:10),rnorm(4))  #執(zhí)行rnorm(4)  
    #由switch(x)來選擇執(zhí)行那個(gè)函數(shù) 
3、while循環(huán)語句
注意執(zhí)行順序,先執(zhí)行f[i]+f[i+1]<1000,然后往下走,與下面repeat有區(qū)別
[plain] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ##while循環(huán)語句  
    #計(jì)算斐波那契數(shù)列  
    f=1  
    f[2]=1  
    i=1  
    while(f[i]+f[i+1]<1000){  
      f[i+2]=f[i]+f[i+1]  
      i=i+1  
    }  
    f  
    #注意執(zhí)行順序,先執(zhí)行f[i]+f[i+1]<1000,然后往下走,與下面repeat有區(qū)別 
4、repeat循環(huán)
常常與if聯(lián)用。
[plain] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ##repeat語句  
    #計(jì)算斐波那契數(shù)列  
    f=1  
    f[2]=1  
    i=1  
    repeat{  
      f[i+2]=f[i]+f[i+1]  
      i=i+1  
      if (f[i]+f[i+1]>1000) break  
    };f  
    #與if常常聯(lián)用,注意執(zhí)行順序,f[i]+f[i+1]>1000,與while<1000不同 
與if常常聯(lián)用,注意執(zhí)行順序,f[i]+f[i+1]>1000,與while<1000不同。
5、if函數(shù)+function
      if和while都是需要數(shù)據(jù)TRUE/FALSE這樣的邏輯類型變量,這就意味著,if內(nèi)部,往往是對(duì)條件的判別,例如 is.na, is.matrix, is.numeric等等,或者對(duì)大小的比較,如,if(x > 0), if(x == 1), if(length(x)== 3)等等。
      if后面,如果是1行,則花括號(hào)可以省略,否則就必須要將所有的語句都放在花括號(hào)中。這和循環(huán)是一致的
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    fun.test <- function(a, b, method = "add"){  
        if(method == "add") { ## 如果if或者for/while;  
            res <- a + b       ## 等后面的語句只有一行,則無需使用花括號(hào)。  
    }  
        if(method == "subtract"){  
            res <- a - b  
        }  
        return(res)           ## 返回值  
    }  
    ### 檢驗(yàn)結(jié)果  
    fun.test(a = 10, b = 8, method = "add")  
    fun.test(a = 10, b = 8, method = "substract") 
同時(shí)if還有類似與excel的用法——ifelse
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ifelse(Age > 30, "Old", "Young") 
Age變量>30,則輸出old;<30,輸出Young
————————————————————————————————————————————————————————————
Function與循環(huán)函數(shù)結(jié)合的實(shí)踐案例
1、函數(shù)如何輸出?——print、return&list
如果是單個(gè)輸出,直接用1.3方法即可
如果有很多輸出項(xiàng)目,那么需要return(終止運(yùn)算,并輸出return中的項(xiàng)目)最終輸出的項(xiàng)目
R中默認(rèn)的情況是將最后一句作為返回值。
1.1 return&list組合
return和list的組合輸出結(jié)果比較合理。(來自R語言︱噪聲數(shù)據(jù)處理、數(shù)據(jù)分組——分箱法(離散化、等級(jí)化))
[html] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
    sbdeep=function(data,parts,xiaoz){  
      parts<-parts         #分幾個(gè)箱  
      xiaoz<-xiaoz         #極小值  
        value<-quantile(data,probs = seq(0,1,1/parts))  #這里以data等比分為4段,步長(zhǎng)為1/4  
      number<-mapply(function(x){  
        for (i in 1:(parts-1))   
        {  
          if(x>=(value[i]-xiaoz)&x<value[i+1])  
          {  
            return(i)  
          }  
        }  
        if(x+xiaoz>value[parts])  
        {  
          return(parts)  
        }  
        return(-1)  
      },data)  
      #打標(biāo)簽L1L2L3L4  
      return(list(degree=paste("L",number,sep=""),degreevalue=number,value=table(value),number=table(number)))               #將連續(xù)變量轉(zhuǎn)化成定序變量,此時(shí)為L(zhǎng)1,L2,L3,L4...根據(jù)parts  
    } 
該函數(shù)是對(duì)單個(gè)序列數(shù)據(jù)進(jìn)行等深分箱,可以返回四類:
一個(gè)基于L1L2L3....的每個(gè)指標(biāo)標(biāo)簽序列degree;
標(biāo)簽序列值degreevalue,
每個(gè)百分位數(shù)對(duì)應(yīng)的變量值value,
不同百分點(diǎn)的數(shù)量number。
1.2 print直接輸出
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片

    function(){  
      print(plot(cv.out))   
    } 
print可以直接輸出.
1.3 直接輸出——一一般都是直接輸出
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片

    function(){  
    a=c(1:50)  
    a  
    } 
其中a就是直接寫在末尾,當(dāng)做輸出項(xiàng)。
2、function中應(yīng)用if switch函數(shù)
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    test=function(mode=c("all", "out", "in")){  
      mode <- switch(mode, out = 1, `in` = 2, all = 3)  
       
      if (as.numeric(mode)==1) {  
        t=1  
      }  
       
      if (as.numeric(mode)==2) {  
        t=2  
      }  
       
      if (as.numeric(mode)==3) {  
        t=3  
      }  
      t=t+1  
      return(t+4)  
    }  
    a=test(mode="out")  
      
    test(mode="in")  
      
    test(mode="all") 
解決場(chǎng)景:編寫函數(shù)時(shí)候,可能嵌套很多模型的時(shí)候,就需要用這個(gè)流程。
switch函數(shù),輸入mode,執(zhí)行相應(yīng)的內(nèi)容,此時(shí)是mode選擇“all”,則執(zhí)行返回1,;mode選擇"out"則返回2;
然后用if去進(jìn)行每個(gè)數(shù)字背后的建模,注意“==”
"in"注意要引號(hào),因?yàn)闀?huì)跟內(nèi)嵌函數(shù)重疊
3 異常值處理——如何報(bào)錯(cuò)
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    # 異常處理,當(dāng)僅輸入一個(gè)數(shù)據(jù)的時(shí)候,告知不能計(jì)算標(biāo)準(zhǔn)差  
     if(length(x) == 1){                            
        stop("can not compute sd for one number,  
             a numeric vector required.\n")         
     } 
————————————————————————————————————
應(yīng)用一:if族有哪些成員呢?——if/ifelse/stopifnot
在函數(shù)中,if的應(yīng)用場(chǎng)景非常多,用來識(shí)別某類情況前提下,再執(zhí)行下一個(gè)。
其中筆者就見過這樣三類if:if-else   ifelse   stopifnot
1、if-else
這個(gè)很常見,就是需要注意一下,if-else的寫法,來看經(jīng)管之家論壇一位壇友的提醒與使用心得:
      if(){}else{}  表示先執(zhí)行if括號(hào)后面的條件語句,如果正確就執(zhí)行第一個(gè)大括號(hào)里的程序,如果錯(cuò)誤就執(zhí)行else后面大括號(hào)里的語句。
      有一種情況,r會(huì)報(bào)錯(cuò):
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    if(){}  
    else{}  
      就是這種情況,即else語句換了一行執(zhí)行時(shí),這是r會(huì)認(rèn)為if語句已經(jīng)執(zhí)行完畢,但執(zhí)行else發(fā)現(xiàn)前面無法執(zhí)行,因此報(bào)錯(cuò),在這里要提醒使用r的同志們,else必須緊挨著if語句后的大括號(hào),這時(shí)才不會(huì)出錯(cuò)。

2、ifelse
      跟If-else其實(shí)是一模一樣的,但是效率提高很多,是提高代碼運(yùn)算效率很高的函數(shù)。ifelse()的句法格式類似于if()函數(shù),但其運(yùn)算速度卻有了巨大的提升。即使是在沒有預(yù)設(shè)數(shù)據(jù)結(jié)構(gòu)且沒有簡(jiǎn)化條件語句的情況下,其運(yùn)算效率仍高于上述的兩種方法。
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    ifelse(test, yes, no) 
      ifelse返回的是結(jié)果,有一點(diǎn)麻煩的是,不像if-else一樣,可以寫一些分布計(jì)算的東西,譬如現(xiàn)在有以下一種情況:
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
    a<-c+d  
    sum(a>2)  #在c大于2的情況下,要計(jì)算a大于2的個(gè)數(shù) 
      這個(gè)分步情況在if-else里面很好解決,但是在ifelse里面可不容易,只能接受一步,所以盡量把運(yùn)算鏈合并在一起。
3、stopifnot
      這個(gè)函數(shù)跟Ifelse有點(diǎn)像,但是很奇特。stopifnot(c>2),如果正確執(zhí)行,那么就會(huì)啥都沒發(fā)生,如果錯(cuò)誤了,就會(huì)跳入Debug模式,報(bào)錯(cuò),讓函數(shù)立刻停下來。
      這個(gè)stopifnot跟trycatch函數(shù)聯(lián)合使用,威力無比。
用tryCatch跳過:
[html] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
    result = tryCatch(  
            {expr},   
            warning = function(w) {warning-handler-code},   
            error = function(e) { error-handler-code},   
            finally = {cleanup-code}  
            ) 
出現(xiàn)warning、error時(shí)候怎么處理,就可以跳過了。例子:
[html] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
    result = tryCatch(  
            {segmentCN(txt)},   
            warning = function(w) {"出警告啦"},   
            error = function(e) { "出錯(cuò)啦"},   
            ) 
分詞時(shí)候,容易因?yàn)長(zhǎng)apply中斷之后,就不會(huì)運(yùn)行了,這樣功虧一簣所以可以用這個(gè)辦法跳過。
————————————————————————————————————
應(yīng)用二:如何在循環(huán)中,實(shí)時(shí)輸出時(shí)間消耗?
   想知道循環(huán)中進(jìn)行到哪里?這樣可以合理安排函數(shù)進(jìn)程。那么怎么辦呢?
      第一辦法:使用Rstudio 1.0版本,里面有一個(gè)Profiling with profvis,可以很好的對(duì)你函數(shù)每一步的耗時(shí)進(jìn)行參看。
當(dāng)然,這個(gè)不能實(shí)時(shí)輸出內(nèi)容。數(shù)據(jù)分析師培訓(xùn)
      第二辦法:利用difftime函數(shù)
[html] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
    t1 = Sys.time()  
    for (i in 1:5){  
    a=a+1  
    b=a*a  
    print(difftime(Sys.time(), t1, units = 'sec'))  
    } 
      先預(yù)設(shè)當(dāng)前時(shí)間,然后用difftime+print方式,循環(huán)輸出。

數(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ù)說明請(qǐng)參見: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); }