R - 应用函数族

时间:2018-02-08 18:09:40

标签: r matrix apply

我是R的初学者。我曾经在VB.NET中编码,我的新挑战是在R中编码。我渴望了解有关 Apply 函数的更多信息。 我目前正在研究6种不同时间序列的矩阵。我想计算我的时间序列的历史方差。 我设法使用下面的2 for循环来做到这一点:

x<-structure(list(`SGIXMTE Index` = c(-5.95019685234609e-05, 
-0.000753736450099747, 
-0.000148875986303415, -0.00149890808020643, 3.97657795584496e-05, 
0.00101398705675335, -0.00047668702517491, -0.00199707889952018, 
-0.00277761185114386, 0.00165723242185547), `SGIXWIT Index` = 
c(-0.000884636343691835, 
-0.012686292287641, 0, -0.0102952254546758, 0.00724900326205147, 
0.013342929111191, -0.00215902957302347, -0.00838434163701066, 
-0.0137953804854941, 0.0135371179039301), `SGIXMTE Index.1` = 
c(-5.95019685234609e-05, 
-0.000753736450099747, -0.000148875986303415, -0.00149890808020643, 
3.97657795584496e-05, 0.00101398705675335, -0.00047668702517491, 
-0.00199707889952018, -0.00277761185114386, 0.00165723242185547
), `SGEPLBE Index` = c(-0.00114345982748901, -0.00144794960926269, 
0.00240278911991955, -0.00413605101129573, 0.000194027111355773, 
0.0108162238114213, -0.00441920174278378, -0.00219335948693103, 
-0.00786854773864096, 0.00765729021393045), `SGIXMTE Index.2` = 
c(-5.95019685234609e-05, 
-0.000753736450099747, -0.000148875986303415, -0.00149890808020643, 
3.97657795584496e-05, 0.00101398705675335, -0.00047668702517491, 
-0.00199707889952018, -0.00277761185114386, 0.00165723242185547
)), .Names = c("SGIXMTE Index", "SGIXWIT Index", "SGIXMTE Index.1", 
"SGEPLBE Index", "SGIXMTE Index.2"), row.names = c(NA, 10L), class = 
"data.frame")

for (j in (1:ncol(x))) {
    if (x[1, j] == "" | is.na(x[1, j])) {
        varianceMat[1, j] = as.numeric(-1)
    } else {
        varianceMat[1, j] = as.numeric(x[1, j]^2)
    }
    for (i in 2:nrow(x)) {
        if (x[i, j] == "" | is.na(x[i, j])) {
            varianceMat[i, j] = as.numeric(ifelse(varianceMat[i - 1, j] != -1, varianceMat[i - 1, j], -1))
        } else {
            varianceMat[i, j] = as.numeric(ifelse(varianceMat[i - 1, j] == -1, x[i, j]^2, (1 - lambda) * (x[i, j]^2) + lambda * varianceMat[i - 1, j]))
        }
    }
}

#Result
              [,1]         [,2]         [,3]         [,4]         [,5]
[1,] 3.540484e-09 7.825815e-07 3.540484e-09 1.307500e-06 3.540484e-09
[2,] 8.822721e-08 2.480650e-05 8.822721e-08 1.425859e-06 8.822721e-08
[3,] 7.831773e-08 2.108552e-05 7.831773e-08 2.077990e-06 7.831773e-08
[4,] 4.035789e-07 3.382144e-05 4.035789e-07 4.332329e-06 4.035789e-07
[5,] 3.432793e-07 3.663043e-05 3.432793e-07 3.688126e-06 3.432793e-07
[6,] 4.460128e-07 5.784093e-05 4.460128e-07 2.068351e-05 4.460128e-07
[7,] 4.131955e-07 4.986400e-05 4.131955e-07 2.051039e-05 4.131955e-07
[8,] 9.494648e-07 5.292898e-05 9.494648e-07 1.815545e-05 9.494648e-07
[9,] 1.964314e-06 7.353651e-05 1.964314e-06 2.471924e-05 1.964314e-06
[10,] 2.081630e-06 8.999407e-05 2.081630e-06 2.980647e-05 2.081630e-06

此代码产生了预期的结果,但我希望有人向我展示代码如何更优雅,特别是使用apply函数。

0 个答案:

没有答案