3

Hello Everyone: I want to have an empty array and then create a for loop to add values to it. Ignore the simple function that's inside "temp_val" my function is more complicated. I just put that here for clarity

This is what I have:

values = numeric()
for (n1 in 1:50) {

        n2 = n1+1
        temp_val = (n1+n2)
        append(values,temp_val)
}

I was hoping that as the for loop iterates 50 times that it would append 50 values from "temp_val" to my empty array "values" however, "values" never gets appended with any of the iterations from "temp val"

Please advise

CloudFiend
  • 33
  • 3
  • 1
    A perfectly fine question, but you might want to also check this previous question out for some efficiency issues with growing a vector - https://stackoverflow.com/questions/22235809/append-value-to-empty-vector-in-r – thelatemail Oct 07 '20 at 01:35
  • 3
    Better initiate the vector at the right length and populate it, better practice and much more performant. `values = numeric(50)`. Then `values[n1] = temp_val ` – moodymudskipper Oct 07 '20 at 01:39

1 Answers1

1

We need to assign (<-) to 'values' to update the original object

for (n1 in 1:50) {

    n2 = n1+1
    temp_val = (n1+n2)
    values <-  append(values,temp_val)
  }

-output

values
#[1]   3   5   7   9  11  13  15  17  19  21  23  25  27  29  31  33  35  37  39  41  43  45  47  49  51  53  55  57  59  61  63  65  67
#[34]  69  71  73  75  77  79  81  83  85  87  89  91  93  95  97  99 101
akrun
  • 874,273
  • 37
  • 540
  • 662
  • *Facepalm* Thank you very very much. I am not sure how I missed that. For some reason I thought append would add it automatically. A very inexperienced person here. But thanks again – CloudFiend Oct 07 '20 at 01:38
  • 1
    @CloudFiend It is a different behavior when compared to Python – akrun Oct 07 '20 at 01:40