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

方法2: 采用 for + if + else 语句

1: 自定义函数
# digital was translated into englishname
Month_name_for_if_else<-function(month){
  Month_name<-c()
  for (i in 1:length(month)){
    if (month[i]==1) Month_name[i]<-"Jan"
    else if (month[i]==2) Month_name[i]<-"Feb"
    else if (month[i]==3) Month_name[i]<-"Mar"
    else if (month[i]==4) Month_name[i]<-"Apr"
    else if (month[i]==5) Month_name[i]<-"May"
    else if (month[i]==6) Month_name[i]<-"Jun"
    else if (month[i]==7) Month_name[i]<-"Jul"
    else if (month[i]==8) Month_name[i]<-"Aug"
    else if (month[i]==9) Month_name[i]<-"sep"
    else if (month[i]==10) Month_name[i]<-"Oct"
    else if (month[i]==11) Month_name[i]<-"Nov"
    else  Month_name[i]<-"Dec"
  }
  return(Month_name)
}
# season data
Season_name_for_if_else<-function(month){
  Season_name<-c()
  for (i in 1:length(month)){
    if (month[i]==1 | month[i]==2 | month[i]==12) Season_name[i]<-"Winter"
    else if (month[i]==3|month[i]==4|month[i]==5) Season_name[i]<-"Spring"
    else if (month[i]==6|month[i]==7|month[i]==8) Season_name[i]<-"Summer"
    else Season_name[i]<-"Winter"
  }
  return(Season_name)
}
result_for_if_else<-function(month){
  Month_name_for_if_else<-Month_name_for_if_else(month)# months' names
  Season_name_for_if_else<-Season_name_for_if_else(month) #seasons' names
  df<-data.frame(month,Month_name_for_if_else,Season_name_for_if_else)
  return(df)
}
2: 调用函数进行运算
month<-month_digital(10) #随机生成10个数据进行测试
microbenchmark::microbenchmark(Month_name_for_if_else(month))
microbenchmark::microbenchmark(Season_name_for_if_else(month))
microbenchmark::microbenchmark(result_for_if_else(month))
Unit: microseconds
                          expr    min     lq     mean  median    uq      max
 Month_name_for_if_else(month) 11.556 11.846 305.4237 12.0485 12.31 29278.45
 neval
   100
Unit: microseconds
                           expr    min      lq     mean  median     uq      max
 Season_name_for_if_else(month) 20.748 21.3765 225.6315 21.7485 22.223 20364.43
 neval
   100
Unit: microseconds
                      expr     min       lq    mean  median      uq      max
 result_for_if_else(month) 667.421 683.8345 806.516 694.004 720.526 6149.171
 neval
   100

(未完!待续……)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值