R中向量中相邻元素的加权平均值

时间:2012-09-24 03:12:41

标签: r

我有两个向量xw。向量w是权重与x相同的数字向量。 我们如何得到向量x中相邻元素的加权平均值(第一个元素和第二个元素的加权平均值,然后是第二个元素和第三个元素的加权平均值,......例如,这些向量是如下:

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)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

函数式编程方法 - 比@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))