1. R语言运行效率分析 (2)
2020-02-01 本文已影响0人
灭绝老衲
方法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
(未完!待续……)