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

方法6: 采用 str_replace_all 语句

1: 自定义函数
Month_name_str_replace_all<-function(month){
  Month_name<-as.character(month)
  Month_name<-str_replace_all(Month_name,"1","Jan")%>%str_replace_all("2","Feb")%>%str_replace_all("3","Mar")%>%str_replace_all("4","Apr")%>%str_replace_all("5","May") %>%str_replace_all("6","Jun")%>%str_replace_all("7","Jul")%>%str_replace_all("8","Aug")%>%str_replace_all("9","Sep")%>%str_replace_all("10","Oct")%>%str_replace_all("11","Nov")%>%str_replace_all("12","Dec")
  return(Month_name)
}
Season_name_str_replace_all<-function(month){
  Season_name<-as.character(month)
  Season_name<-str_replace_all(Season_name,"12|1|2","Winter")%>%str_replace_all("3|4|5","Spring")%>%str_replace_all("6|7|8","Summer")%>%str_replace_all("9|10|11","Autumn")
  
  return(Season_name)
}
result_str_replace_all<-function(month){
  Month_name_str_replace_all<-Month_name_str_replace_all(month)# months' names
  Season_name_str_replace_all<-Season_name_str_replace_all(month) #seasons' names
  df<-data.frame(month,Month_name_str_replace_all,Season_name_str_replace_all)
  return(df)
}
2: 调用函数进行运算
month<-month_digital(10)
microbenchmark::microbenchmark(Month_name_str_replace_all(month))
microbenchmark::microbenchmark(Season_name_str_replace_all(month))
microbenchmark::microbenchmark(result_str_replace_all(month))
Unit: milliseconds
                              expr      min       lq     mean   median       uq
 Month_name_str_replace_all(month) 2.015145 2.189275 3.372382 2.522119 3.269861
      max neval
 32.74809   100
Unit: microseconds
                               expr   min      lq     mean  median       uq
 Season_name_str_replace_all(month) 714.5 728.566 1145.484 746.193 1230.856
      max neval
 11526.32   100
Unit: milliseconds
                          expr    min       lq     mean   median       uq
 result_str_replace_all(month) 3.5555 3.621327 4.431068 3.706999 4.130232
     max neval
 12.0781   100

(未完!待续……)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值