0

I'd like to sum up consecutive values in one column by groups, without long explanation, I have df like this:

set.seed(1)
gr <- c(rep('A',3),rep('B',2),rep('C',5),rep('D',3))
vals <- floor(runif(length(gr), min=0, max=10))
idx <- c(seq(1:3),seq(1:2),seq(1:5),seq(1:3))
df <- data.frame(gr,vals,idx)

   gr vals idx
1   A    2   1
2   A    3   2
3   A    5   3
4   B    9   1
5   B    2   2
6   C    8   1
7   C    9   2
8   C    6   3
9   C    6   4
10  C    0   5
11  D    2   1
12  D    1   2
13  D    6   3

And I'm looking for this one:

   gr vals idx
1   A    2    1
2   A    5    2
3   A    10   3
4   B    9    1
5   B    11   2
6   C    8    1
7   C    17   2
8   C    23   3
9   C    29   4
10  C    29   5
11  D    2    1
12  D    3    2
13  D    9    3

So ex. in group C we have 8+9=17 (first and second element of the group) and second value is replaced by the sum. Then 17+6=23 (sum of previously summed elements and third element), 3rd element replaced by the new result and so on... I was looking for some solution here but it isn't what I'm looking for.

Adamm
  • 2,150
  • 22
  • 30

1 Answers1

0

Ok, I think I got it

df %>%
  group_by(gr) %>%
  mutate(nvals = cumsum(vals))
   gr     vals   idx    nvals
 1 A         2     1     2
 2 A         3     2     5
 3 A         5     3    10
 4 B         9     1     9
 5 B         2     2    11
 6 C         8     1     8
 7 C         9     2    17
 8 C         6     3    23
 9 C         6     4    29
10 C         0     5    29
11 D         2     1     2
12 D         1     2     3
13 D         6     3     9
Adamm
  • 2,150
  • 22
  • 30