[R] weighted mean by week

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Wed Jul 18 00:17:55 CEST 2012


Hello!

I wrote a code that works, but it looks ugly to me - it's full of loops.
I am sure there is a much more elegant and shorter way to do it.
Thanks a lot for any hints!
Dimitri

# I have a data frame:
x<-data.frame(group=c("group1","group2","group1","group2"),
  myweight=c(0.4,0.6,0.4,0.6),
  myweek=as.Date(c("2012-07-09","2012-07-09","2012-07-16","2012-07-16")),
  var1=c(1,10,2,20),var2=c(10,1,20,2))
(x)

# For each week in "myweek", I'd like to build a weighted mean for
var1 and var2  - using  "myweight" as weight.
# Below is my inelegant code:

myweeks<-unique(x$myweek)
nr.of.weeks<-length(myweeks)
myvars<-c("var1","var2")

mylist<-NULL
for(i in 1:nr.of.weeks){  	# i<-1
  out<-NULL
  for(var in myvars){		# var<-myvars[2]
	temp.x<-x[x$myweek %in% myweeks[i],c("myweight",var)]
	temp.out<-weighted.mean(temp.x[[2]],temp.x[[1]])
	out<-c(out,temp.out)
  }
  mylist[[i]]<-out
  names(mylist)[i]<-as.character(myweeks[i])
}
desired<-as.data.frame(do.call(rbind,mylist))
names(desired)<-myvars
(desired)

-- 
Dimitri Liakhovitski
marketfusionanalytics.com



More information about the R-help mailing list