[英]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.它基本上是最后 k 个值的总和,但它乘以 n/k,其中 n 是最后 k 个元素的索引。
for the given x as input the output will have following values对于给定的 x 作为输入,output 将具有以下值
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
Use rollapply with the indicated function:将 rollapply 与指示的 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))
An alternative that allows us to omit the k = k argument is:允许我们省略 k = k 参数的替代方法是:
wsum <- function(x, k = length(x)) sum(seq(k) * x) / k
transform(x, ret = rollapply(ret, k, wsum, align = "left", fill = NA))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.