Home > Enterprise >  Adding Next Number to Previous number in Vector in R, For Loop
Adding Next Number to Previous number in Vector in R, For Loop

Time:04-18

I am super new to coding and am trying to make a little for loop in R. The idea is to add each subsequent index in the numbers loop and output it to a new vector called sums. So, the sums vector should look like (10,19,27,34,40,45,49,52,54,55).

numbers<-seq(10,1, by=-1)
Output: [1] 10  9  8  7  6  5  4  3  2  1
sums<-c()

Here is what I have tried:

for (i in numbers) {
  sums[i]<-sum(numbers[i 1])
  print(sums)
}

Output: [1]  9  8  7  6  5  4  3  2  1 NA NA

for (i in numbers) {
  sums[i]<-sum(numbers[i})
  print(sums)
}

Output: 55

CodePudding user response:

Use the cumulative sum function

cumsum(10:1)

CodePudding user response:

I'd do this

sums <- cumsum(10:1)
sums

If you want to use a for loop, you could do something like this:

e.g.

numbers<- 10:1

# this creates a blank vector
sums <- c()

for (i in seq_along(numbers)) {
  sums <-c(sums, sum(numbers[1:i]))
}

print(sums)

If you put print inside the loop, it's going to print at every iteration of the loop

  • Related