美文网首页
1. R语言运行效率分析(5)

1. R语言运行效率分析(5)

作者: 灭绝老衲 | 来源:发表于2020-02-04 21:22 被阅读0次

    方法5: 采用 which 语句

    1: 自定义函数

    # digital was translated into englishname
    Month_name_which<-function(month){
      Month_name<-month
      Month_name[(which(Month_name==1))]<-"Jan"
      Month_name[(which(Month_name==2))]<-"Feb"
      Month_name[(which(Month_name==3))]<-"Mar"
      Month_name[(which(Month_name==4))]<-"Apr"
      Month_name[(which(Month_name==5))]<-"May"
      Month_name[(which(Month_name==6))]<-"Jun"
      Month_name[(which(Month_name==7))]<-"Jul"
      Month_name[(which(Month_name==8))]<-"Aug"
      Month_name[(which(Month_name==9))]<-"Sep"
      Month_name[(which(Month_name==10))]<-"Oct"
      Month_name[(which(Month_name==11))]<-"Nov"
      Month_name[(which(Month_name==12))]<-"Dec"
      
      return(Month_name)
    }
    Season_name_which<-function(month){
      Season_name<-month
      Season_name[which(Season_name %in% c(12,1,2))]<-"Winter"
      Season_name[which(Season_name %in% c(3,4,5))]<-"Spring"
      Season_name[which(Season_name %in% c(6,7,8))]<-"Summer"
      Season_name[which(Season_name %in% c(9,10,11))]<-"Autumn"
     
      return(Season_name)
    }
    result_which<-function(month){
      Month_name_which<-Month_name_which(month)# months' names
      Season_name_whichh<-Season_name_which(month) #seasons' names
      df<-data.frame(month,Month_name_which,Season_name_whichh)
      return(df)
    }
    

    2: 调用函数进行运算

    month<-month_digital(10)
    microbenchmark(Month_name_which(month))
    microbenchmark(Season_name_which(month))
    microbenchmark(result_which(month))
    
    Unit: microseconds
                        expr    min      lq     mean median      uq      max neval
     Month_name_which(month) 71.668 73.2195 393.5091 74.426 76.0145 31879.35   100
    Unit: microseconds
                         expr    min      lq     mean median     uq      max neval
     Season_name_which(month) 42.812 43.9625 157.1115 44.655 45.477 11199.92   100
    Unit: microseconds
                    expr    min       lq     mean  median       uq      max neval
     result_which(month) 771.61 786.8795 886.8605 800.243 829.8675 4943.644   100
    

    (未完!待续……)

    相关文章

      网友评论

          本文标题:1. R语言运行效率分析(5)

          本文链接:https://www.haomeiwen.com/subject/ncidxhtx.html