如何在R中的for循环内的向量中存储值

如何在R中的for循环内的向量中存储值

本文介绍了如何在R中的for循环内的向量中存储值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 R,但我对以下问题感到非常沮丧:我试图将在 for 循环中完成的某些计算的值存储到我之前定义的向量中.问题是如何做索引,因为for循环将执行的次数迭代代码取决于用户的输入,所以变量i不一定要从1开始,它可以从80开始例如,这就是为什么它很困难.

I'm getting started in R but I'm really frustrated with the following problem: I'm trying to store the value of some calculation done inside a for loop into a vector I have previously defined. The problem is how to do the indexing, because the number of times the for loop will be executed to iterate the code depends on the user's input, so the variable i doesn't have to start at 1 necessarily, it can start at 80 for example, and this is why it is difficult.

我在其他 StackOverflow 帖子上搜索了很多,但没有找到我正在寻找的答案.这其实是我第一次提问,因为我很固执.我想过创建另一个 for 循环,但不知道它是如何工作的.我确信有一个简单的解决方案,但也许我还不知道确切的功能,因为我还在学习.

I have searched a lot on other StackOverflow posts but haven't found the answer I'm looking for. This is actually the first time I ask a question since I'm very stubborn. I have thought of creating another for loop but don't know how it would work. I'm certain there's an easy solution to this but maybe I don't know the exact function yet since I'm still learning.

my_vector <- vector(mode="numeric")

#Suppose the user's input was 80:84, which gets stored in "number",
#where "number" is just a function argument that encompasses everything,
#and on which the for loop depends therefore

for(i in number) {
    #insert the calculation here, let's say it is i+3
    result <- i+3
    my_vector[i] <- result
}

我希望 my_vector 的长度为 4(在这种情况下)并包含数字 83、84、85 和 86,但是对于 my_vector,使用 i 索引的索引从 80 开始,而不是从 1 开始,这就是问题所在.

I would like my_vector to be of length 4 (in this case) and include the numbers 83, 84, 85, and 86, but indexing with i starts with 80 for my_vector, not with 1 and this is the problem.

如何根据迭代将这 4 个结果存储在 my_vector 索引中,从 1 到 4?

How do I get those 4 results stored in my_vector indexing from 1 to 4 depending on the iteration?

非常感谢.

推荐答案

您可以使用 append() 将元素添加到向量的末尾:

You can use append() to add an element to the end of a vector:

my_vector <- vector(mode="numeric")

number <- 80:84

for(i in number) {
    #insert the calculation here, let's say it is i+3
    result <- i+3
    my_vector <- append(my_vector, result)
}

注意:您不需要为此使用 for 循环.由于 R 中的加法运算符是矢量化的,您可以这样做:

Note: You don't need to use a for loop for this. Since the addition operator in R is vectorized, you can just do:

my_vector <- number + 3

这篇关于如何在R中的for循环内的向量中存储值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 15:21