Bensor Beny
Bensor Beny

Reputation: 285

weighted average of neighbor elements in a vector in R

I have two vectors x and w. vector w is a numerical vector of weights the same length as x. How can we get the weighted average of neighbor elements in vector x( weighted average of the first element and second one , then weighted average of the secnod and third elements, ..... For example, these vectors are as follows:

x = c(0.0001560653, 0.0001591889, 0.0001599698, 0.0001607507, 0.0001623125,
      0.0001685597, 0.0002793819, 0.0006336307, 0.0092017241, 0.0092079042,
      0.0266525118, 0.0266889564, 0.0454923285, 0.0455676525, 0.0457005450)

w = c(2.886814e+03, 1.565955e+04, 9.255762e-02, 7.353589e+02, 1.568933e+03,
      5.108046e+05, 6.942338e+05, 4.912165e+04, 9.257674e+00, 3.609918e+02,
      8.090436e-01, 1.072975e+00, 1.359145e+00, 9.828314e+00, 9.455688e+01)

Upvotes: 3

Views: 633

Answers (2)

mnel
mnel

Reputation: 115392

A functional programming approach - will be slower than `@David Robinsons

# lots of `Map` \ functional programming
mapply(weighted.mean,
 x = Map(c, head(x,-1),tail(x,-1)), 
 w = Map(c, head(w,-1) ,tail(w,-1))

Upvotes: 1

David Robinson
David Robinson

Reputation: 78610

sapply(1:(length(x)-1), function(i) weighted.mean(x[i:(i+1)], w[i:(i+1)]))

Upvotes: 3

Related Questions