Table of Cumulative Totals R

Viewed 54

I am trying to replace counts in a table with the cumulative totals row-wise. In the example below the first row currently reads 8, 12, 1, 6, 6, and I want it to read 8, 20, 21, 27, 33. I know I could do this through a loop, but there must be a simpler way. I would love to do this outside the tidyverse if possible.

o <- structure(c(8, 1, 9, 2, 3, 2, 25, 12, 15, 21, 19, 17, 6, 90, 
1, 19, 23, 22, 14, 5, 84, 6, 20, 31, 28, 28, 12, 125, 6, 23, 
37, 28, 25, 15, 134), .Dim = c(7L, 5L), .Dimnames = structure(list(
    c("1", "2", "3", "4", "5", "6", "Sum"), c("1", "2", "3", 
    "4", "5")), .Names = c("", "")), class = "table")
print( o )
3 Answers

We could use rowCumsums from matrixStats

library(matrixStats)
o[] <-  rowCumsums(o)

-output

> o
     
        1   2   3   4   5
  1     8  20  21  27  33
  2     1  16  35  55  78
  3     9  30  53  84 121
  4     2  21  43  71  99
  5     3  20  34  62  87
  6     2   8  13  25  40
  Sum  25 115 199 324 458

Another option is fcumsum with dapply (collapse)

library(collapse)
dapply(o, MARGIN = 1, FUN = fcumsum)

-output

        1   2   3   4   5
  1     8  20  21  27  33
  2     1  16  35  55  78
  3     9  30  53  84 121
  4     2  21  43  71  99
  5     3  20  34  62  87
  6     2   8  13  25  40
  Sum  25 115 199 324 458

In same spirit as akrun's answer, but using R base functions:

> o[] <- t(apply(o, 1, cumsum))
> o
     
        1   2   3   4   5
  1     8  20  21  27  33
  2     1  16  35  55  78
  3     9  30  53  84 121
  4     2  21  43  71  99
  5     3  20  34  62  87
  6     2   8  13  25  40
  Sum  25 115 199 324 458

This is just another solution:

do.call(rbind, Reduce(function(x, y) {
  x + as.matrix(o)[, y]
}, 2:dim(o)[2], init = as.matrix(o)[, 1], accumulate = TRUE)) |> t()

    [,1] [,2] [,3] [,4] [,5]
1      8   20   21   27   33
2      1   16   35   55   78
3      9   30   53   84  121
4      2   21   43   71   99
5      3   20   34   62   87
6      2    8   13   25   40
Sum   25  115  199  324  458
Related