My dataset:

    Item_Id    Year_Month
 B65623262     201204
 B58279745     201204
 B33671102     201204
 B36630946     201204
 B63270151     201204
 B63270133     201204



 I have written my code to calculate one more column which is the product
maturity time as the following:

launchtime<-function(g){

su<-data.frame(NULL)    #product maturity time

g<-g[order(g$Item_Id,g$Year_Month),]

#get the lauching time
index2<-unique(g$Item_Id)

for(u in 1:length(index2)){
m2<-g[g$Item_Id==index2[u],]

lt<-numeric(0)
lt[1]<-0
year<-as.numeric(substring(m2$Year_Month,1,4))
month<-as.numeric(substring(m2$Year_Month,5,6))
if(dim(m2)[1]==1){}else{
 for(i in 1:(dim(m2)[1]-1)){
j<-i+1
lt[j]<-(12*(year[j]-year[1])+month[j])-(month[1])
}}
g2<-cbind(m2,lt)
su<-rbind(su,g2)
}

return(su)

}



How to optimize my code-. it takes so long time to run.


Kind regards,
Tammy

	[[alternative HTML version deleted]]

