Last answered:

03 Oct 2022

Posted on:

30 Sept 2022

0

Resolved: Creating an empty vector with variable length

Hello,

In the previous lecture, we explicitly defined the length of an empty vector "new.title <- vector(length=5)", so it can store 5 elements from the For loop.

Is it possible to create an empty vector that can store a variable number of elements?
For instance, I apply the Collatz conjecture for this while loop:

x <- 10
x
while (x != 1) {
  if ((x %% 2) == 0) {
    x <- x / 2
  } else {
    x <- x * 3 + 1
  }
  print(x)
}



Since we can set any positive integer for x, we would also have different number of results from the Collatz conjecture before it reaches 1.
So, instead of "printing" the new value of vector x on each cycle, I want to store them in a vector first, then just print the vector once the loop breaks.

Kind regards,
Carl

1 answers ( 1 marked as helpful)
Instructor
Posted on:

03 Oct 2022

0

Hi Carl,
yes, you can create a vector, or character array which you can gradually fill in the for loop. To do so, you can define the array like so:

my_vec <- character()            # Create empty character vector
my_vec 

Then you can fill it up with the value of x in the for loop like so:

while (x != 1) {
  if ((x %% 2) == 0) {
    x <- x / 2
    my_vec <- c(my_vec, x)
  } else {
    x <- x * 3 + 1
    my_vec <- c(my_vec, x) } }

Let me know if the solution works for you.

Best,
365 Eli

Submit an answer