caproki
caproki

Reputation: 410

How to store values in a vector inside a for loop in R

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.

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
}

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.

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

Thank you very much.

Upvotes: 3

Views: 11535

Answers (2)

Roman
Roman

Reputation: 4989

Is there a reason you want to use a loop / function? You can use directly the vectorized (and fast)

number <- 80:84
result <- number + 3

resulting in

> number
[1] 83 84 85 86 87

If, for some reason, you really want the operation to be handled in a loop, you should at least pre-allocate the vector.

result <- rep(0, length(number))

for(i in 1:length(number)) {
    result[i] <- number[i] + 3
}

Upvotes: 0

Brigadeiro
Brigadeiro

Reputation: 2945

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)
}

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

Upvotes: 2

Related Questions