方法8: 采用 ddply 语句
1: 自定义函数
Month_name_ddply<-function(month){
Month<-as.data.frame(month)
Month$ID<-1:nrow(Month)
df<-ddply(Month,.(month),function(x){mutate(x,month_name=month.abb[month])})
Month_name<-arrange(df,ID)
return(Month_name[,-2])
}
Season_name_ddply<-function(month){
Month<-as.data.frame(month)
Month$ID<-1:nrow(Month)
df<-ddply(Month,.(month),function(x){mutate(x,season_name=c("Winter","Winter","Spring","Spring","Spring","Summer","Summer","Summer","Autumn","Autumn","Autumn","Winter")[month])})
Season_name<-arrange(df,ID)
return(Season_name[,-2])
}
result_ddply<-function(month){
Month_name_ddply<-Month_name_ddply(month)# months' names
Season_name_ddply<-Season_name_ddply(month) #seasons' names
df<-data.frame(month,Month_name_ddply,Season_name_ddply)
return(df)
}
2: 调用函数进行运算
month<-month_digital(10)
microbenchmark::microbenchmark(Month_name_ddply(month))
microbenchmark::microbenchmark(Season_name_ddply(month))
microbenchmark::microbenchmark(result_ddply(month))
Unit: milliseconds
expr min lq mean median uq max
Month_name_ddply(month) 8.760018 8.888448 9.836038 8.980004 9.211437 21.86194
neval
100
Unit: milliseconds
expr min lq mean median uq max
Season_name_ddply(month) 8.731989 8.853146 9.877732 8.976706 9.128971 25.45839
neval
100
Unit: milliseconds
expr min lq mean median uq max
result_ddply(month) 17.98596 18.18733 19.24074 18.27565 18.64888 33.03697
neval
100
(未完!待续……)
网友评论