[R] My code is too "loopy"

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Mon Apr 25 22:50:10 CEST 2011


Hello!
I wrote a piece of code below that does the job but seems too "loopy" to me.
I was wondering if there is any way to make it more efficient/less "loopy"?
Thanks a lot for your hints!
Dimitri

### Creating example data set:

mygroups<-c(rep("group1", 8),rep("group2", 8))
myweeks<-seq(as.Date("2010-01-04"), length = 8, by = "week")
values.w<-c(0,10,15,20,0,0,0,10,100,200,0,0,300,200,0,0)
mydata<-data.frame(group=mygroups,mydates=myweeks,myvalue=values.w)
mydata$group<-as.factor(mydata$group)
str(mydata)
(mydata)

### Doing the following within each level of the factor "mydata$group":
### Create a new variable ("new.value") that equals:
### myvalue in the same week * 0.5 +
### myvalue 1 week ago  * 0.35
### myvalue 2 weeks ago * 0.15

groups<-levels(mydata$group)
(groups)

mydata[["new.value"]]<-mydata[["myvalue"]]*0.5

for(i in groups){   # looping through groups
  temp.data<-mydata[mydata$group %in% i,] # selecting values for one group
  temp.data[2,"new.value"]<-temp.data[["new.value"]][2]+temp.data[1,"myvalue"]*0.35
# 2nd new value
  for(myrow in 3:nrow(temp.data)){  # Starting in row 3 and looping through rows
    temp.data[myrow,"new.value"]<-temp.data[["new.value"]][myrow]+temp.data[(myrow-1),"myvalue"]*.35+temp.data[(myrow-2),"myvalue"]*.15
  }
  mydata[mydata$group %in% i,]<-temp.data
}


-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list