Skip to content
Related Articles

Related Articles

Element-wise concatenation of string vector in R
  • Last Updated : 07 Apr, 2021

Element wise concatenation of two vectors means concurrently taking values from two vectors and joining or concatenating them into one. For this paste() function is used in the R programming language.

Syntax:

paste(vector1,vector2,….,vectorn)

Where, vectors are the inputs to paste function

Example 1:



R




# create a vector named as first_names
first_names=c("sravan","bobby","mohan","sai")
  
# create a vector named as middle_names
middle_names=c("kumar","kumari","pavan","kumar")
  
# apply paste function
print(paste(first_names,middle_names))


Output:

[1] “sravan kumar” “bobby kumari” “mohan pavan”  “sai kumar”

We can combine n vector elements at a time

Example: 2 

R




# create a vector named as first_names
first_names=c("sravan","bobby","mohan","sai")
  
# create a vector named as middle_names
middle_names=c("kumar","kumari","pavan","kumar")
  
# create a vector named as middle_names
last_names=c("H","B","G","M")
  
# apply paste function
print(paste(first_names,middle_names,last_names))


Output:

[1] “sravan kumar H” “bobby kumari B” “mohan pavan G”  “sai kumar M” 



If we do not need to give a gap between two concatenated strings use paste0() function.

Syntax:

paste0(vector1,vector2,…,vectorn)

Example:

R




# create a vector named as first_names
first_names=c("sravan","bobby","mohan","sai")
  
# create a vector named as middle_names
middle_names=c("kumar","kumari","pavan","kumar")
  
# create a vector named as middle_names
last_names=c("H","B","G","M")
  
# apply paste0 function fro combining first and middlename
print(paste0(first_names,middle_names))
  
# apply paste0 function fro combining first  middlename and last names
print(paste0(first_names,middle_names,last_names))


Output:

[1] “sravankumar” “bobbykumari” “mohanpavan”  “saikumar”

[1] “sravankumarH” “bobbykumariB” “mohanpavanG”  “saikumarM” 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :