Stupid_Intern
Stupid_Intern

Reputation: 3450

Calculate rolling sum product

If I have following variables

x <- data.frame(ret = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) )
k <- 4

and I want to get y such that

y[i,1] = x[i,1]*(1/k) + x[i+1,1]*(2/k) + x[i+2,1]*(3/k) + x[i+3,1]*(k/k)
.
.
.

till i = nrow(x) - k + 1

how can I achieve this?

It is basically sum of last k values but it is multiplied by n/k where n is the index of last k elements.

for the given x as input the output will have following values

y
7.5   <- y[1,1] = (x[1,1] * 0.25 + x[2,1] *0.5 + x[3,1]  *0.75 +  1 * x[4,1])
10
12.5
15
17.5
20
22.5
25
27.5
30
32.5
35

Upvotes: 1

Views: 126

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

Use rollapply with the indicated function:

library(zoo)

wsum <- function(x, k) sum(seq(k) * x) / k 
transform(x, ret = rollapply(ret, k, wsum, k = k, align = "left", fill = NA))

Update

An alternative that allows us to omit the k = k argument is:

wsum <- function(x, k = length(x)) sum(seq(k) * x) / k 
transform(x, ret = rollapply(ret, k, wsum, align = "left", fill = NA))

Upvotes: 2

Related Questions