R program to append values to vector using Loop?

In this article, we will discuss how to append values to a vector using a loop in R Programming Language

In R programming language, you can use a loop to append values to a vector. The most common loop in R is the "for" loop. Here is an example of how to append values to a vector using a for loop: 

 

# create an empty vector
my_vector <- vector()

# create a for loop to append values to the vector
for(i in 1:5){
  my_vector <- c(my_vector, i)
}

# print the vector
print(my_vector)

In this example, we first create an empty vector called "my_vector" using the vector() function. We then use a for loop to append values to the vector. The loop iterates over the sequence 1:5 and appends each value to the vector using the c() function. Finally, we print the vector to see the output.

Another way to append values to a vector using a loop is by using the append() function. Here is an example: 

 

# create an empty vector
my_vector <- vector()

# create a for loop to append values to the vector
for(i in 1:5){
  my_vector <- append(my_vector, i)
}

# print the vector
print(my_vector)

In this example, we use the append() function to append each value to the vector within the for loop. The append() function takes two arguments: the vector and the value to append.

Submit Your Programming Assignment Details