R代码迭代 [英] R code iteration

查看:199
本文介绍了R代码迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是使用 iter 在R中生成此向量:

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.

推荐答案

你可以这样做:

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

这篇关于R代码迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆