R code iteration

2019-07-04 00:03发布

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.

标签: r iteration
1条回答
Melony?
2楼-- · 2019-07-04 00:32

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
查看更多
登录 后发表回答