You are currently viewing How to Concatenate Vector in R

To concatenate a vector or multiple vectors in R use c() function. This c() function is used to combine the objects by taking two or multiple vectors as input and returning the vector with the combined elements from all vectors.

By using c() function you can also combine vectors of different types but all the elements of the resultant R vector would be of the same type. Additionally, use append() function to combine vectors.

1. Quick Examples of Concatenate Vectors

Following are quick examples of how to concatenate vectors in R.


# Quick Examples

# Combine vectors
v1 <- c('A','B','C')
v2 <- c('X','Y','Z')
v3 <- c(v1,v2)
print(v3)

# Combine different type vectors
v1 <- c('A','B','C')
v2 <- c(1,2,3)
v3 <- c(v1,v2)
print(v3)

# append()
v4 <- append(v1,v2)
print(v4)

2. Combine Function Syntax

The following is a concatenate function syntax. Note the following, when you use c() to concatenate vectors.

  • Use c() to combine two or more vectors
  • This function can take multiple vectors as arguments
  • It accepts different types of vectors
  • Returns all elements of the same type.

# Syntax of c()
c(argument, argument,..)

This function takes argument objects you wanted to combine and return the combined object of the same type.

3. Concatenate Vectors

Use the c() function to concatenate a vector or multiple vectors in R. This function takes arguments of vectors you wanted to combine and returns a single vector.

The following example concatenates two vectors v1 and v2 into v3 with all the elements from both vectors.


# Combine vectors
v1 <- c('A','B','C')
v2 <- c('X','Y','Z')
v3 <- c(v1,v2)
print(v3)

Yields below output.

r concatenate vectors

4. Concatenate Different Types of Vectors

By using this c() function you can also combine vectors of different types but all the elements of the resultant vector would be of the same type. Let’s create a vector of character type and another vector of numeric type and combine these two vectors and validate the result.


# Combine vectors
v1 <- c('A','B','C')
v2 <- c(1,2,3)
v3 <- c(v1,v2)
print(v3)

Yields below output.

You can check the type of combined vector by using typeof() function.

5. By using append()

Use append() function to add a single element or multiple elements to the vector. This function is also used to append vectors in R.


# using append()
v1 <- c('A','B','C')
v2 <- c(1,2,3)
v3 <- append(v1,v2)
print(v3)

6. Conclusion

In this article, you have learned how to concatenate a vector or multiple vectors in R by using c() and append() functions. c() is a combined function that takes multiple objects, combines them, and returns a single object of the same type. You can find the complete example from this article at Github R Programming Examples Project.

Related Articles

References