Open In App
Related Articles

Append Operation on Vectors in R Programming

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, let us discuss different methods to concatenate/append values to a vector in R Programming Language. 

Append method in R

Vectors in the R Programming Language is a basic objects consisting of sequences of homogeneous elements. vector can be integer, logical, double, character, complex, or raw. Values can be appended/concatenated in a vector using 2 methods.

  1. c() function
  2. append() function 
  3. Using indexing

1. Append operation using c() function

c() function is a generic function that combines data into a vector or a list.

Syntax: c(…)
Parameters: 
…: represents objects to be concatenated 

To know about more optional parameters, use the below command in the console: 

help("c")

Append using c() function

r

# Create a vector
x <- 1:5
n <- 6:10
 
# Append using c() function
y <- c(x, n)
 
# Print resultant vector
print(y)

                    

Output: 

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

Append method using c() function for different type of variables
 

r

# Create vector
x <- 1:5
n <- letters[1:5]
 
# Append
y <- c(x, n)
 
# Print resultant vector
print(y)
 
# Print type of resultant vector
typeof(y)
 
# Print type of other vectors
typeof(x)
typeof(n)

                    

Output: 

[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
[1] "character"
[1] "integer"
[1] "character"

2. Append operation using append() function

append() function in R is used for merging vectors or adding more elements to a vector.

Syntax: append(x, values)
Parameters: 
x: represents a vector to which values has to be appended to 
values: represents the values which has to be appended in the vector 

Append operation using append() function

r

# Create a vector
x <- 1:5
 
# Append using append() function
x <- append(x, 6:10)
 
# Print resultant vector
print(x)

                    

Output: 

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

Append operation using append() function for different type of variables

r

# Create a vector
x <- 1:5
y <- letters[1:5]
 
# Append using append() function
x <- append(x, values = y)
 
# Print resultant vector
print(x)

                    

Output: 

[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"

3. Append operation Using indexing

We can also append elements using indexing. we can assign values to indices beyond the length of the vector to append new elements.

R

# Create a vector
my_vector <- c(1, 2, 3, 4)
 
# Append elements using indexing
my_vector[5] <- 5
my_vector[6] <- 6
 
my_vector

                    

Output:

[1] 1 2 3 4 5 6


Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads