简体   繁体   English

R 动态data.frame中的累积和

[英]R cumulative sum in dynamic data.frame

df <- data.frame('a'=c(1,2,3,4,5), 'M1'=c(1,20,3,4,50))

Now I want to create an additional 179 columns (M2 - M180) which is dependent on the sum of previous Mx columns.现在我想创建一个额外的 179 列 (M2 - M180),这取决于先前 Mx 列的总和。 For instance, M2 should be the sum for all previous Mx values ie M1 in this case.例如,M2 应该是所有先前 Mx 值的总和,即本例中的 M1。 And M3 should be the sum M1+M2 and so on all the way to M180. M3 应该是 M1+M2 之和,以此类推一直到 M180。

The expected result for the first three Mx columsn should be:前三个 Mx 列的预期结果应该是:

Expected_res <- data.frame('a'=c(1,2,3,4,5), 'M1'=c(1,20,3,4,50), 'M2'=c(1,20,3,4,50), 'M3'=c(2,40,6,8,100))

Basically I want the excel equivalent to Sum($E1:E1) and then dragging it out for 180 columns, for each row of course.基本上我想要 excel 相当于 Sum($E1:E1) 然后将其拖出 180 列,当然是每一行。

Any help is appreciated.任何帮助表示赞赏。

You can use a for loop:您可以使用for循环:

for(i in 2:180) {
  df[paste0('M', i)] <- rowSums(df[-1])
}

-1 ignores the 1st column ( a ) and takes sum of all other columns to create a new column. -1忽略第一列( a )并取所有其他列的总和来创建一个新列。

Here's the output of first 5 columns.这是前 5 列的 output。

df
#  a M1 M2  M3  M4  M5
#1 1  1  1   2   4   8
#2 2 20 20  40  80 160
#3 3  3  3   6  12  24
#4 4  4  4   8  16  32
#5 5 50 50 100 200 400

using tidyverse使用tidyverse

library(tidyverse)
df <- data.frame('a'=c(1,2,3,4,5), 'M1'=c(1,20,3,4,50))
n <- 5
bind_cols(df, map_dfc(seq_len(n), ~transmute(df, !!paste0("M", .x + 1) := M1 * 2 ^ (.x - 1))))
#>   a M1 M2  M3  M4  M5  M6
#> 1 1  1  1   2   4   8  16
#> 2 2 20 20  40  80 160 320
#> 3 3  3  3   6  12  24  48
#> 4 4  4  4   8  16  32  64
#> 5 5 50 50 100 200 400 800

Created on 2021-02-02 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 2 月 2 日创建

using data.table使用data.table

library(data.table)
df <- data.frame('a'=c(1,2,3,4,5), 'M1'=c(1,20,3,4,50))
setDT(df)
n <- 5
col_names <- paste0("M", seq_len(n) + 1)
df[, (col_names) := lapply(seq_len(n), function(x) M1 * 2 ^ (x - 1))]
df
#>    a M1 M2  M3  M4  M5  M6
#> 1: 1  1  1   2   4   8  16
#> 2: 2 20 20  40  80 160 320
#> 3: 3  3  3   6  12  24  48
#> 4: 4  4  4   8  16  32  64
#> 5: 5 50 50 100 200 400 800

Created on 2021-02-02 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 2 月 2 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM