dplyr :: mutate中的矩阵乘法

时间:2018-08-21 13:05:30

标签: r dplyr matrix-multiplication

structure(list(var = c(8L, 9L, 3L, 1L, 7L, 4L, 6L, 2L, 5L, 10L
), rate = c(1, 0.99, 0.9801, 0.970299, 0.96059601, 0.9509900499, 
0.941480149401, 0.93206534790699, 0.92274469442792, 0.913517247483641
)), class = "data.frame", row.names = c(NA, -10L))

使用上述数据,我想使用以下公式https://imgur.com/a/eKjlQBe计算新变量,其中n是行号,x分别命名为var和{{1 }}(后续权力在我的数据中存储为lambda = 0.99)。因此,我想对rate中的列的子集使用矩阵乘法,但这没有用。

dplyr::mutate

如何计算根据上述公式定义的新列? 所需的输出如下所示:

df %>% mutate(out = rate[1:row_number()] %*% var[row_number():1])

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式获得所需的结果

df <- structure(list(var = c(8L, 9L, 3L, 1L, 7L, 4L, 6L, 2L, 5L, 10L
), rate = c(1, 0.99, 0.9801, 0.970299, 0.96059601, 0.9509900499, 
            0.941480149401, 0.93206534790699, 0.92274469442792, 0.913517247483641
)), class = "data.frame", row.names = c(NA, -10L))
df$out <- sapply(1:nrow(df), function(i) sum(df$var[1:i]*df$rate[i:1]))
df
# > df
#    var      rate      out
# 1    8 1.0000000  8.00000
# 2    9 0.9900000 16.92000
# 3    3 0.9801000 19.75080
# 4    1 0.9702990 20.55329
# 5    7 0.9605960 27.34776
# 6    4 0.9509900 31.07428
# 7    6 0.9414801 36.76354
# 8    2 0.9320653 38.39590
# 9    5 0.9227447 43.01194
# 10  10 0.9135172 52.58182