带计算的矩阵列的累计和

Cumulative sums of matrix columns with calculation

我有一个如下所示的矩阵:

           date     1   2   3   4
          201601    2   4   6   1
          201602    3   7   7   4
          201603    4   8   9   6
          201604    6   4   5   7

行表示 prod_Date 列 header(1 到 4)年龄。数字表示产品的销售额。

我需要生成一个数据框,其中包含 PER YEAR,销售额的计算总和,而且,我想将其乘以 "maturity" 由 Age/max(Age) 给出的因子- 在这种情况下,例如 1/4 或 2/4。请注意年龄可能会有所不同。 最终输出应如下所示:

     age    cum.sales   sales*maturity
     1           15         3.75
     2           38        19.00
     3           65        48.75
     4           83        83.00

关于如何快速完成的任何建议? 提前致谢

假设初始数据集是 data.frame(因为 matrix 不能保持混合 class 否则 'date' 将是 'numeric' class。如果它是一个数字 class,下面的解决方案仍然有效)。从 matrix/data.framemutate 的列名创建一个 data.frame,其中 'age' 作为列,以创建 'cum.sales'(从获取列总和的累积总和没有 'date' 列的数据集)和 'salesmaturity' 通过将 'cum.sales' 乘以 'age' 的分数与 max(age).

library(dplyr)
d1 <- data.frame(age = as.numeric(colnames(df1)[-1])) 
d1 %>% 
    mutate(cum.sales = cumsum(colSums(df1[-1])), 
            salesmaturity = cum.sales*age/max(age))
#   age cum.sales salesmaturity
#1   1        15          3.75
#2   2        38         19.00
#3   3        65         48.75
#4   4        83         83.00

数据

df1 <- structure(list(date = 201601:201604, `1` = c(2L, 3L, 4L, 6L), 
`2` = c(4L, 7L, 8L, 4L), `3` = c(6L, 7L, 9L, 5L), `4` = c(1L, 
4L, 6L, 7L)), .Names = c("date", "1", "2", "3", "4"),
class = "data.frame", row.names = c(NA, -4L))