Weighted mean by row

前端 未结 1 380
灰色年华
灰色年华 2020-12-19 11:50

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,w         


        
相关标签:
1条回答
  • 2020-12-19 12:03

    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
    
    0 讨论(0)
提交回复
热议问题