标签:
#包的下载 install.packages("RODBC") #数据包 #MYSQL链接 library(RODBC) channel<-odbcConnect(dsn="mysql") odbcGetInfo(channel=channel) #得到数据库信息 start_date<-"2015-01-01" close_date<-as.character(Sys.Date()-1) sql<-paste("select","Date,2_industry,todayConsume","from","industry2_consume","where","Date",">=","‘",start_date,"‘","and","Date","<","‘",close_date,"‘","and","2_departmentID=200","and","2_industry!=‘其他‘",";",sep=" ") raw_data<-sqlQuery(channel=channel,query=sql) #数据消费处理 col_consuption<-raw_data[order(raw_data[,2]),] matrix_consuption<-split(col_consuption$todayConsume,list(col_consuption[[2]])) matrix_industry_result<-do.call(‘cbind‘,matrix_consuption) frame_industry_result<-data.frame(matrix_industry_result) #移动平均 ma<-function(cdata){ ldata<-cdata ldata<-cbind(ldata,SMA(cdata,7)) ldata<-cbind(ldata,SMA(cdata,14)) ldata<-na.locf(ldata,fromLast=TRUE) return(ldata) } result<-lapply(frame_industry_result,ma) final_result<-NULL for (i in 1:length(result)){ final_result<-cbind(final_result,result[[i]]) } name_result<-NULL for (i in 1:length(names(frame_industry_result))){ name_result<-c(name_result,paste(names(frame_industry_result)[i],c("","7天日均","14天日均消费"),sep="")) } dimnames(final_result)[[2]]<-list(name_result)[[1]] length_date=max(col_consuption$Date)-min(col_consuption$Date)+1 Date<-col_consuption$Date[1:length_date] final_result_Date<-cbind(final_result,as.character(Date)) list_names_result<-list(name_result)[[1]] list_names_result[length(list(name_result)[[1]])+1]<-c("日期") dimnames(final_result_Date)[[2]]<-list_names_result write.csv(final_result_Date,file="D:/result.csv")
第二次写的程序,虽然看得很复杂,但是我会继续努力的。
标签:
原文地址:http://www.cnblogs.com/xiongchang18/p/4504046.html