Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted mean by row

Tags:

r

I have the following data:

a=c(1:10)
b=c(16:25)
c=c(24:33)
wa=c(3,7,3,3,3,3,3,3,3,1)
wb=c(3,2,3,3,3,3,3,3,3,8)
wc=c(4,1,4,4,4,4,4,4,4,1)
z=data.frame(a,b,c,wa,wb,wc)

I want to get the weighted mean for each record. So I tried this:

weight=apply(subset(z,select=c(wa,wb,wc)),1,function(x) x)
z$weightMean=apply(subset(z,select=c(a,b,c)),1,function(x) weighted.mean(x,weight))

Which returned the following error message:

Error in weighted.mean.default(x, weight) : 
  'x' and 'w' must have the same length

So then I tried this:

weight=as.vector(weight)
z$weightMean=apply(subset(z,select=c(a,b,c)),1,function(x) weighted.mean(x,weight))

Which also returned the same error.

What am I doing wrong?

like image 690
thequerist Avatar asked Mar 25 '12 22:03

thequerist


1 Answers

This seems to do the trick:

> apply(z, 1, function(x) weighted.mean(x[1:3], x[4:6]))
 [1] 14.7  7.3 16.7 17.7 18.7 19.7 20.7 21.7 22.7 24.3

This will probably be a bit faster, though less clear as to what's going on:

> rowSums(z[,1:3] * z[,4:6]) / rowSums(z[,4:6])
 [1] 14.7  7.3 16.7 17.7 18.7 19.7 20.7 21.7 22.7 24.3
like image 53
Chase Avatar answered Oct 01 '22 05:10

Chase