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

方法4: 采用 for + switch 语句

1: 自定义函数

# digital was translated into englishname
Month_name_for_switch<-function(month){
  Month_name<-c()
  for (i in 1:length(month)){
    Month_name[i]<-switch(as.character(month[i]),
                           "1"="Jan","2"="Feb","3"="Mar",
                           "4"="Apr","5"="May", "6"="Jun",
                           "7"="Jul","8"="Aug", "9"="Sep",
                           "10"="Oct","11"="Nov","12"="Dec"
    )
  }
  return(Month_name)
}
# season data
Season_name_for_switch<-function(month){
  Season_name<-c()
  for (i in 1:length(month)){
    Season_name[i]<-switch(as.character(month[i]),
                           "1"="winter","2"="winter","3"="spring",
                           "4"="spring","5"="spring", "6"="summer",
                           "7"="summer","8"="summer", "9"="autumn",
                           "10"="autumn","11"="autumn","12"="winter"
    )
  }
  return(Season_name)
}
result_for_switch<-function(month){
  Month_name_for_switch<-Month_name_for_switch(month)# months' names
  Season_name_for_switch<-Season_name_for_switch(month) #seasons' names
  df<-data.frame(month,Month_name_for_switch,Season_name_for_switch)
  return(df)
}

2: 调用函数进行运算

month<-month_digital(10)
Month_name_for_switch(month)
Season_name_for_switch(month)
microbenchmark::microbenchmark(Month_name_for_switch(month))
microbenchmark::microbenchmark(Season_name_for_switch(month))
microbenchmark::microbenchmark(result_for_switch(month))
Unit: microseconds
                         expr   min     lq     mean median     uq      max
 Month_name_for_switch(month) 17.17 17.718 93.07517 17.958 18.333 7425.695
 neval
   100
Unit: microseconds
                          expr    min      lq     mean  median     uq      max
 Season_name_for_switch(month) 16.981 17.5185 87.48225 17.7105 17.952 6984.314
 neval
   100
Unit: microseconds
                     expr     min      lq     mean   median       uq      max
 result_for_switch(month) 670.175 682.519 772.8128 692.1065 704.6855 4726.116
 neval
   100

(未完!待续……)

发布了13 篇原创文章 · 获赞 14 · 访问量 707

猜你喜欢

转载自blog.csdn.net/fan_xiao_hui/article/details/104154382