How to add numbers in series in R (using a forloop)?

Let's say I have a vector
x: 0 1 2 3 4 5
I would like to have a
result: 0 1 3 6 10 15

I tried the for loop but was not successful. Any help in this regard will be app reciated

You could use accumulate from the purrr package for this.

library(purrr)

x <- list(0, 1, 2, 3, 4, 5)  ### Example data

### Option #1 with 'sum' function.
accumulate(x, sum)

### Option #2 with '+' operator
accumulate(x, `+`)
1 Like

Here is another approach using a for loop.

x = c(0, 1, 2, 3, 4, 5)
x_new = c()

for(i in 1:length(x)) {
  x_new = c(x_new, sum(x[1:i]))
}

x
#> [1] 0 1 2 3 4 5
x_new
#> [1]  0  1  3  6 10 15

Created on 2022-11-17 with reprex v2.0.2.9000

1 Like

None of this requires loops:

cumsum(0:5)
4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.