方法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
(未完!待续……)