如何使用函数内的范围值对给定范围内的函数求和

时间:2017-02-13 17:58:29

标签: r function time-series

我有以下公式,其中b是固定值(求和的上限):

\sum_{a=3}^{b=5}(a/b)cov{(k(t),k(t-a))}

K(t)是给定系列k的t值,k(t-a)是滞后a的值:

k<- rnorm(100, 1, .25)

我的尝试:

(3/5)*cov(k,lag(k,k=3)) + (4/5)*cov(k,lag(k,k=4)) + (5/5)*cov(k,lag(k,k=5)) 
  

答案:0.08400983

我需要评估最多20个各种值的总和。举例说明:

b= 5:(3/5)*cov(k,lag(k,k=3)) + (4/5)*cov(k,lag(k,k=4)) + (5/5)*cov(k,lag(k,k=5))
b = 6: (3/6)*cov(k,lag(k,k=3)) + (4/6)*cov(k,lag(k,k=4)) + (5/6)*cov(k,lag(k,k=5)) +(6/6)*cov(k,lag(k,k=6))
b = 7: (3/7)*cov(k,lag(k,k=3)) + (4/7)*cov(k,lag(k,k=4)) + (5/7)*cov(k,lag(k,k=5)) +(6/7)*cov(k,lag(k,k=6)) + (7/7)*cov(k,lag(k,k=7))

我很困惑如何在给定的时间间隔内对此进行总结。请帮我在R中开发此功能。谢谢

1 个答案:

答案 0 :(得分:2)

我会做这样的事情:

foo = function(k, start = 3, stop = 5) {
    result = 0
    for (i in start:stop) {
        result = result + i / stop * cov(k, stats::lag(k, k = i))
    }
    return(result)
} 

测试它是否有效:

k = rnorm(100)
foo(k)

现在迭代不同的stop值。我在这里使用sapply而不是for循环,因为它更像R-like。

stops = 5:20
res = cbind(stops, sapply(stops, function(b) foo(k, start = 3, stop = b)))
res
#       stops         
#  [1,]     5 2.240816
#  [2,]     6 2.801020
#  [3,]     7 3.334547
#  [4,]     8 3.851402
#  [5,]     9 4.357142
#  [6,]    10 4.855101
#  [7,]    11 5.347401
#  [8,]    12 5.835458
#  [9,]    13 6.320249
# [10,]    14 6.802476
# [11,]    15 7.282651
# [12,]    16 7.761159
# [13,]    17 8.238293
# [14,]    18 8.714283
# [15,]    19 9.189310
# [16,]    20 9.663518