Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

r - Weighted mean by row

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...