Question

My goal is to generate this vector in R using iter:

0 + 1 = 1,

1 + 2 = 3,

3 + 3 = 6,

6 + 4 = 10

I tried the code below, but it didn't give me the right numbers:

iter <- 4
w_vector <- rep(0, iter)
for(i in 1:iter) {w_vector[i] <-sum(i, i-1)
                  print(w_vector[i])
}

I'll truly appreciate it if you can help me fix my code.

Was it helpful?

Solution

You can do:

w_vector <- cumsum(seq(iter))
w_vector
# [1]  1  3  6 10

Otherwise, using a for loop, your code should look something like:

iter <- 4
w_vector <- rep(0, iter)
w_vector[1] <- 1
for(i in 2:iter) {
  w_vector[i] <- w_vector[i-1] + i
}
w_vector
# [1]  1  3  6 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top