简体   繁体   English

如何使用R中的for循环填充列表?

[英]How to fill up a list using a for loop in R?

My goal is to create a list of numerical values starting at a lower bound a to an upper bound b with n equal increments.我的目标是创建一个数值列表,从下限 a 到上限 b,以 n 相等的增量开始。 I have to that for very large values.对于非常大的值,我必须这样做。 I thought that using a for loop would easily do the work, but it is not working and I can't see where my mistake is.我认为使用 for 循环可以轻松完成工作,但它不起作用,我看不出我的错误在哪里。

I use the following code and it returns NA我使用以下代码,它返回 NA

a <- 20
b <- 2
n <- 18
inc < (a-b)/n

l <-c(b)

for ( i in n) {
l[i+1] <- l[i] + inc
}

I expected the following result我期待以下结果

[2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 ,19 , 20]

Instead, I get the following : [2 , NA , NA , ... ]相反,我得到以下信息: [2 , NA , NA , ... ]

Okay I figured it out.好吧,我想通了。 I had to initiate the list with the right space by adding this piece of code before.我之前必须通过添加这段代码来用正确的空间启动列表。 l <- numeric(n) and then I adde the first element to initialize it. l <- numeric(n)然后我添加第一个元素来初始化它。 l[1] <- b

Sorry, rookie mistake !对不起,菜鸟错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM