How to append an empty array in R

Viewed 564

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

1 Answers

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
Related