1
df <- as_tibble(a <- c(1,2,3))
df
# A tibble: 3 x 1
  value
  <dbl>
1     1
2     2
3     3

The goal is this:

# A tibble: 3 x 2
  value   Sum
  <dbl>   
1     1   1
2     2   3
3     3   6

So just display the sum after each row. 1 = 1. 1+2 = 3. 3+3 = 6, and so on. I guess it's kinda easy, maybe with rowSums?

Dutschke
  • 277
  • 2
  • 15

1 Answers1

1

It is a cumulative sum. In R, there is cumsum to do that

df$Sum <- cumsum(df$value)

We could do the same while constructing the 'tibble

library(tibble)
df <- tibble(value = 1:3, Sum = cumsum(value))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks. I googled it for a while but couldn't find this function. I guess i just used the wrong words? – Dutschke Sep 17 '20 at 16:02
  • @Dutschke with google, if you don't use the right key words, it may take time to get to exact page – akrun Sep 17 '20 at 16:03
  • 1
    @Dutschke May be you queried `sum after each row` that can yield a different response i.e. for me, the first page showed [this](https://stackoverflow.com/questions/3991905/sum-rows-in-data-frame-or-matrix) i.e. it parsed as row sums – akrun Sep 17 '20 at 16:04
  • 1
    That's exactly what i did in some variations... cumulative would have been the key word. – Dutschke Sep 17 '20 at 16:05