Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to Append Values to Vector Using Loop in R?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Appending values to an empty vector

Here we are going to append the values using for loop to the empty vector.

Syntax:

for(iterator in range) {
  vector = c(vector, iterator)
}

where,

  • range is the range of values
  • iterator is to iterate the range of values
  • c(vector,iterator) is an append function which will append values to the vector

Example:

R




# create empty vector
vector1 = c()
  
# display
print(vector1)
  
# use for loop to add elements from 1 to 5
for(i in 1: 5) {
    vector1 = c(vector1, i)
}
  
# display
vector1

Output:

NULL
[1] 1 2 3 4 5

Perform Operation and Append Values to Vector

Here we are going to perform some numeric operations and append values to the empty vector. We can perform cube operation and append to empty vector.

Syntax:

for(iterator in range) {
 vector = c(vector, operation(iterator))
}

where,

  • range is the range of values
  • iterator is to iterate the range of values
  • c(vector,operation(iterator) ) is an append function which will append values to the vector by performing some operation

Here we are going to append the cube values to the vector

Example:

R




# create empty vector
vector1 = c()
  
# display
print(vector1)
  
# use for loop to add elements from 
# 1 to 5 with cube values
for(i in 1: 5) {
    vector1 = c(vector1, i*i*i)
}
  
# display
vector1

Output:

NULL
[1]   1   8  27  64 125

Append a Single Value to Vector

Here we are going to append a value for an existing vector.

Syntax:

c(existing_vector,new)

where,

  • existing_vector is the vector
  • new is the values to be appended

Example:

R




# create  vector
vector1 = c(1, 2, 3, 4, 5)
  
# display
print(vector1)
  
# append 34
vector1 = c(vector1, 34)
  
# display
vector1

Output:

[1] 1 2 3 4 5
[1]  1  2  3  4  5 34

Append Multiple Values to Existing Vector

Here we are going to append multiple values to the existing vector using for loop.

Syntax:

for(iterator in range) {
 vector = c(existing_vector, iterator)
}

where,

  • range is the range of values
  • iterator is to iterate the range of values
  • c(existing_vector,iterator) is an append function which will append values to the existing  vector

Example:

R




# create  vector
vector1 = c(6, 7, 8, 9, 10)
  
# display
print(vector1)
  
# use for loop to add elements from 1 to 5
for(i in 1: 5) {
    vector1 = c(vector1, i)
}
  
# display
vector1

Output:

[1]  6  7  8  9 10
[1]  6  7  8  9 10  1  2  3  4  5

My Personal Notes arrow_drop_up
Last Updated : 28 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials