简体   繁体   中英

Weighted lagged calculation in R

I have a couple of datasets(short examples below)

> print(partOne)
 [1]  0.010966943 -0.006819522 -0.007189830  0.039736714  0.002013070
 [6] -0.043946666  0.003808415  0.199010991 -0.094001478 -0.053006526
[11] -0.051489992  0.019122283 -0.011215761  0.057408738 -0.020809564
[16] -0.041295915  0.010134001 -0.011398076
> print(part2)
 [1] 0.13070012 0.15793754 0.06980192 0.13270089 0.11384798 0.24417631
 [7] 0.10363273 0.09182783 0.12217490 0.47649356 0.33660955 0.23079863
[13] 0.21581061 0.13967763 0.05988797 0.28255164 0.16277804 0.12716975
[19] 0.19299641 0.21452418

I need to weight each partOne value by the current part2 value divided by the sum of N previous part2 values.

So, for the short example above (which has 20 values in each array) , a pseudo-code would be:

  1. Skip to item N+1 (eg assume N=10 for this example)
  2. Calculate (partOne[11]*partTwo[11])/sum(partTwo[1->10])
  3. Increment +1
  4. Calculate (partOne[12]*partTwo[12])/sum(partTwo[2->11])
  5. etc. etc.

Try this

x[11:20]*y[11:20]/sapply(1:10,function(t) sum(y[t:(t+9)]))

Data

x <- rnorm(20)
y <- rnorm(20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM