[R] My code is too "loopy"

From: Dimitri Liakhovitski <dimitri.liakhovitski_at_gmail.com>
Date: Mon, 25 Apr 2011 16:50:10 -0400


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

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Mon 25 Apr 2011 - 20:53:26 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 25 Apr 2011 - 22:10:33 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive